Compare commits

...
6 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 3db5e83f0a chore: release 4.6.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:33:14 +01:00
MrBlakeandClaude Opus 5.5 3df4e6a9fc feat: ignore switch VLANs and remember VLAN decisions per profile
- New "ignore" choice: the VLAN is neither created nor assigned and is left
  out of interface labels and the VLAN column
- VLAN decisions are stored once per profile and shared by all switches;
  per-switch decisions from 4.5.0 are migrated on load
- Review dialog shows one row per VID; only open VLANs are listed, stored and
  unambiguous ones sit in a collapsed, editable section

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:33:14 +01:00
MrBlakeandClaude Opus 5.5 f729473b64 chore: release 4.5.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:18:10 +01:00
MrBlakeandClaude Opus 5.5 29d3724a7f feat: map switch VLANs across the tenant group, custom name and tenant for new VLANs
- Match switch VLANs to NetBox VLANs of the switch's tenant group by VID;
  own tenant, site and similar names decide between several candidates
- Review dialog: choose the NetBox VLAN per VID, skip it or create it with a
  custom name and a tenant of the tenant group
- Never create a VLAN twice when "create new" stays stored in the profile

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:18:09 +01:00
MrBlakeandClaude Opus 5.5 535a5e9699 chore: release 4.4.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 13:46:43 +01:00
MrBlakeandClaude Opus 5.5 83787142d3 feat: review missing prefixes, VRFs and VLANs; enforce tenants
- Review dialog gains "Networks" and "VLANs" tabs: VRF per network (global,
  tenant VRF or new VRF), missing prefixes and VLANs are only created when
  ticked; existing tenant VLANs are assigned to ports (802.1Q mode,
  untagged/tagged)
- Read VLAN names from the configuration (Comware now reads the full
  current-configuration)
- Switch IP addresses follow the chosen VRF instead of always global
- Tenant required: switches without tenant are refused; IPs, prefixes, VRFs,
  VLANs and cables get the switch's tenant; client import requires a tenant
  and client IP addresses now get it too
- Fix clipped combo boxes in the review dialog tables

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 13:46:42 +01:00
12 changed files with 692 additions and 33 deletions

No files matched your search

+14
View File
@@ -62,6 +62,20 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- **Mapping review** before the preview: non-obvious port mappings and every - **Mapping review** before the preview: non-obvious port mappings and every
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
any device of the switch's tenant group. Choices are stored in the profile any device of the switch's tenant group. Choices are stored in the profile
- Networks and VLANs in the same review: per network the VRF (global, a tenant
VRF or a new one) and whether a missing prefix is created
- VLAN mapping: switch VLANs are matched to NetBox VLANs of the switch's tenant
group by VID (own tenant, site and similar names decide between several);
each VLAN can be mapped manually, skipped or created with a name and a tenant
of the tenant group of your choice (pre-filled from the switch configuration
and the switch's tenant). VLANs can also be **ignored** on all switches –
they are neither created nor assigned and are left out of the labels. VLAN
decisions are stored per profile (shared by all its switches); only VLANs
that still need a decision are shown, stored and unambiguous ones are in a
collapsed section that can be expanded for editing. Mapped VLANs are assigned
to the ports (802.1Q mode, untagged/tagged)
- Tenant required: a switch without tenant in NetBox is refused; every created
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
- Cables from LLDP/CDP, also with FQDN system names or via the management IP - Cables from LLDP/CDP, also with FQDN system names or via the management IP
- The switch configuration is only changed when "Enable LLDP if needed" is - The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on explicitly switched on
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.3.0" #define AppVersion "4.6.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.3.0" APP_VERSION = "4.6.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"
+5 -4
View File
@@ -231,12 +231,12 @@ class ClientSyncEngine:
if not dry_run: if not dry_run:
device.update(updates) device.update(updates)
if interfaces: if interfaces:
changes.extend(self._sync_interfaces(device, client, dry_run, report)) changes.extend(self._sync_interfaces(device, client, tenant_id, dry_run, report))
if not changes: if not changes:
report["devices_unchanged"] += 1 report["devices_unchanged"] += 1
return changes return changes
def _sync_interfaces(self, device, client, dry_run, report): def _sync_interfaces(self, device, client, tenant_id, dry_run, report):
changes = [] changes = []
existing = {str(item.name).casefold(): item for item in self.nb.dcim.interfaces.filter(device_id=device.id)} existing = {str(item.name).casefold(): item for item in self.nb.dcim.interfaces.filter(device_id=device.id)}
primary = None primary = None
@@ -257,7 +257,7 @@ class ClientSyncEngine:
if record is not None and mac and not dry_run: if record is not None and mac and not dry_run:
assign_mac(self.nb, record, mac, "dcim.interface") assign_mac(self.nb, record, mac, "dcim.interface")
for address in interface.get("ips", []): for address in interface.get("ips", []):
ip, change = self._sync_ip(address, record, interface.get("dhcp"), dry_run, report) ip, change = self._sync_ip(address, record, interface.get("dhcp"), tenant_id, dry_run, report)
if change: if change:
changes.append(change) changes.append(change)
if ip is not None and primary is None and ":" not in address and interface.get("gateway"): if ip is not None and primary is None and ":" not in address and interface.get("gateway"):
@@ -266,7 +266,7 @@ class ClientSyncEngine:
device.update({"primary_ip4": primary.id}) device.update({"primary_ip4": primary.id})
return changes return changes
def _sync_ip(self, address, interface, dhcp, dry_run, report): def _sync_ip(self, address, interface, dhcp, tenant_id, dry_run, report):
matches = [ip for ip in self.nb.ipam.ip_addresses.filter(address=address.split("/")[0]) matches = [ip for ip in self.nb.ipam.ip_addresses.filter(address=address.split("/")[0])
if related_id(ip, "vrf") is None] if related_id(ip, "vrf") is None]
if not matches: if not matches:
@@ -276,6 +276,7 @@ class ClientSyncEngine:
ip = self.nb.ipam.ip_addresses.create({ ip = self.nb.ipam.ip_addresses.create({
"address": address, "status": "dhcp" if dhcp else "active", "address": address, "status": "dhcp" if dhcp else "active",
"assigned_object_type": "dcim.interface", "assigned_object_id": interface.id, "assigned_object_type": "dcim.interface", "assigned_object_id": interface.id,
**({"tenant": tenant_id} if tenant_id else {}),
}) })
return ip, f"IP-Adresse {address} anlegen" return ip, f"IP-Adresse {address} anlegen"
ip = matches[0] ip = matches[0]
+9
View File
@@ -116,6 +116,8 @@ def empty_profile(name):
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name. # Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {}, "cluster_map": {},
"host_map": {}, "host_map": {},
# Switch VLAN decisions for all switches: "<vid>" -> {"action": "map"|"new"|"skip"|"ignore", ...}.
"vlan_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),
} }
@@ -164,6 +166,7 @@ class ProfileStore:
"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", {})), "host_map": dict(record.get("host_map", {})),
"vlan_map": dict(record.get("vlan_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}},
}) })
@@ -171,6 +174,11 @@ class ProfileStore:
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}")) profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for switch in record.get("switches", []): for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}")) profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from 4.5: VLAN decisions were stored per switch.
for switch in profile["switches"]:
for vid, choice in (switch.pop("vlan_map", None) or {}).items():
profile["vlan_map"].setdefault(vid, choice)
switch.pop("create_vlans", None)
# Migration from v2: one VMware source embedded in each profile. # Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"): if not profile["sources"] and record.get("esxi_host"):
@@ -228,6 +236,7 @@ class ProfileStore:
"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", {})), "host_map": dict(profile.get("host_map", {})),
"vlan_map": dict(profile.get("vlan_map", {})),
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)), "clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
}) })
+321 -15
View File
@@ -34,7 +34,7 @@ IP_COMMANDS = {
CONFIG_COMMANDS = { CONFIG_COMMANDS = {
"aruba_cx": "show running-config", "aruba_cx": "show running-config",
"aruba_aos": "show running-config", "aruba_aos": "show running-config",
"hpe_comware": "display current-configuration interface", "hpe_comware": "display current-configuration",
} }
LLDP_CONTROL = { LLDP_CONTROL = {
@@ -732,6 +732,17 @@ def _parse_comware_vlans(config):
return result return result
def parse_vlan_names(config):
"""``{VLAN ID: name}`` from ``vlan <id>`` blocks (same syntax on all platforms)."""
names = {}
for match, body in _config_blocks(config or "", re.compile(r"^vlan\s+(\d+)\s*$", re.I)):
for line in body:
name = re.match(r'^name\s+"?(.*?)"?\s*$', line, flags=re.I)
if name and name.group(1):
names[int(match.group(1))] = name.group(1)
return names
def parse_vlans(config, platform): def parse_vlans(config, platform):
"""VLAN membership per port, keyed by :func:`interface_key`.""" """VLAN membership per port, keyed by :func:`interface_key`."""
if not config: if not config:
@@ -810,6 +821,7 @@ def build_snapshot(outputs, platform):
"raw": {**{key: value for key, value in outputs.items() if key != "config"}, "raw": {**{key: value for key, value in outputs.items() if key != "config"},
**({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})}, **({"vlan_config": _vlan_config_excerpt(outputs["config"])} if outputs.get("config") else {})},
"vlans_read": bool(outputs.get("config")), "vlans_read": bool(outputs.get("config")),
"vlan_names": parse_vlan_names(outputs.get("config", "")),
"lldp_disabled": outputs.get("lldp_disabled", False), "lldp_disabled": outputs.get("lldp_disabled", False),
"lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False), "lldp_enabled_automatically": outputs.get("lldp_enabled_automatically", False),
"discovered_at": time.time(), "discovered_at": time.time(),
@@ -1028,9 +1040,153 @@ def candidate_devices(nb, device):
return scope, sorted(rows, key=lambda row: row["name"].casefold()) return scope, sorted(rows, key=lambda row: row["name"].casefold())
def _require_tenant(device):
tenant_id = related_id(device, "tenant")
if tenant_id:
return tenant_id, None
return None, (f"NetBox-Gerät „{device.name}“ hat keinen Mandanten – bitte zuerst in NetBox einen Mandanten "
"zuweisen. Ohne Mandant werden keine Objekte angelegt.")
def snapshot_networks(snapshot):
"""Networks of all interface IP addresses (host routes are left out)."""
networks = set()
for interface in snapshot["interfaces"]:
for address in interface.get("ip_addresses", []):
network = ipaddress.ip_interface(address).network
if network.prefixlen < network.max_prefixlen:
networks.add(network)
return [str(network) for network in sorted(networks, key=lambda item: (item.version, item))]
def snapshot_vlan_ids(snapshot):
vids = set()
for interface in snapshot["interfaces"]:
vlans = interface.get("vlans") or {}
vids.update(vlans.get("untagged", []))
vids.update(vlans.get("tagged", []))
return sorted(vids)
VLAN_METHODS = {
"vid": "gleiche VID",
"name": "VID + Name",
"ambiguous": "mehrdeutig",
"manual": "manuell",
"new": "fehlt",
"skip": "nicht zuordnen",
"ignore": "ignoriert",
}
def ignored_vlans(vlan_map):
"""VLAN IDs the user chose to ignore on all switches of the profile."""
return {int(vid) for vid, choice in (vlan_map or {}).items() if (choice or {}).get("action") == "ignore"}
def without_vlans(vlans, ignored):
"""Port VLAN membership without ignored VLANs (``None`` stays ``None``)."""
if not vlans or not ignored:
return vlans
return dict(vlans, untagged=[vid for vid in vlans.get("untagged", []) if vid not in ignored],
tagged=[vid for vid in vlans.get("tagged", []) if vid not in ignored])
def candidate_vlans(nb, tenant_id):
"""VLANs of the switch's tenant group (or tenant) – a VLAN may belong to a
sibling tenant, e.g. a school network documented under its own tenant."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
found = {}
sources = [nb.ipam.vlans.filter(tenant_id=tenant_id)]
if group_id:
sources.append(nb.ipam.vlans.filter(tenant_group_id=group_id))
for source in sources:
for vlan in source:
found[vlan.id] = vlan
return list(found.values())
def candidate_tenants(nb, tenant_id):
"""Tenants a new VLAN may get: the tenant group of the switch's tenant."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
tenants = {tenant_id: getattr(tenant, "name", None) or str(tenant_id)}
if group_id:
tenants.update({item.id: item.name for item in nb.tenancy.tenants.filter(group_id=group_id)})
return sorted(({"id": key, "name": value} for key, value in tenants.items()), key=lambda row: row["name"].casefold())
def _name_tokens(text):
return set(re.findall(r"[a-z]+|\d+", (text or "").casefold()))
def vlan_choice_label(vlan):
owner = getattr(getattr(vlan, "tenant", None), "name", None) or getattr(getattr(vlan, "group", None), "name", None)
return f"{vlan.vid} – {vlan.name}" + (f" ({owner})" if owner else "")
def match_vlans(vids, names, vlans, tenant_id, site_id, manual=None):
"""Assign NetBox VLANs to switch VLAN IDs.
Candidates need the same VID. With several, the own tenant, the switch's
site and similar names (``Server_LEO`` ↔ ``Leo Server``) decide.
``manual`` is ``{str(vid): {"action": "map"|"new"|"skip", "id", "name"}}``.
Returns ``{vid: (record or None, method, name for a new VLAN)}``.
"""
manual = manual or {}
by_vid, by_id = {}, {vlan.id: vlan for vlan in vlans}
for vlan in vlans:
by_vid.setdefault(vlan.vid, []).append(vlan)
result = {}
for vid in vids:
switch_name = names.get(vid) or f"VLAN{vid}"
choice = manual.get(str(vid)) or {}
if choice.get("action") == "new":
name = (choice.get("name") or switch_name)[:64]
# Created by an earlier run – use it instead of creating it again.
created = next((vlan for vlan in by_vid.get(vid, []) if vlan.name.casefold() == name.casefold()), None)
result[vid] = (created, "manual", name) if created else (None, "new", name)
continue
if choice.get("action") in ("skip", "ignore"):
result[vid] = (None, choice["action"], switch_name)
continue
if choice.get("action") == "map" and choice.get("id") in by_id:
result[vid] = (by_id[choice["id"]], "manual", switch_name)
continue
candidates = by_vid.get(vid, [])
if not candidates:
result[vid] = (None, "new", switch_name)
continue
tokens = _name_tokens(switch_name)
def score(vlan):
other = _name_tokens(vlan.name)
similarity = len(tokens & other) / len(tokens | other) if tokens | other else 0
return ((related_id(vlan, "tenant") == tenant_id) * 4 + (related_id(vlan, "site") == site_id) * 2
+ similarity * 3)
ranked = sorted(candidates, key=score, reverse=True)
if len(ranked) == 1:
method = "vid"
else:
method = "name" if score(ranked[0]) > score(ranked[1]) else "ambiguous"
result[vid] = (ranked[0], method, switch_name)
return result
def _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id):
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
vlans = candidate_vlans(nb, tenant_id)
return vlans, match_vlans(snapshot_vlan_ids(snapshot), names, vlans, tenant_id, site_id, config.get("vlan_map"))
def plan_switch_sync(nb, config, snapshot): def plan_switch_sync(nb, config, snapshot):
"""Proposed interface mapping and neighbor devices for the review dialog.""" """Proposals for the review dialog: interface mapping, neighbor devices,
networks (VRF and missing prefixes) and missing VLANs."""
device, error = _resolve_device(nb, config) device, error = _resolve_device(nb, config)
if not error:
tenant_id, error = _require_tenant(device)
if error: if error:
return {"error": error} return {"error": error}
records = list(nb.dcim.interfaces.filter(device_id=device.id)) records = list(nb.dcim.interfaces.filter(device_id=device.id))
@@ -1053,12 +1209,50 @@ def plan_switch_sync(nb, config, snapshot):
known.add(remote.id) known.add(remote.id)
neighbors.append(dict(neighbor, device_id=device_id, method=method)) neighbors.append(dict(neighbor, device_id=device_id, method=method))
devices.sort(key=lambda row: row["name"].casefold()) devices.sort(key=lambda row: row["name"].casefold())
tenant_vrfs = {vrf.id: vrf.name for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)}
vrfs = sorted(tenant_vrfs.values(), key=str.casefold)
stored_vrfs = config.get("network_vrfs") or {}
create_prefixes = config.get("create_prefixes")
networks = []
for network in snapshot_networks(snapshot):
# Where the prefix already exists: "" = global, otherwise a tenant VRF.
existing = set()
for prefix in nb.ipam.prefixes.filter(prefix=network):
vrf_id = related_id(prefix, "vrf")
if vrf_id is None or vrf_id in tenant_vrfs:
existing.add(tenant_vrfs.get(vrf_id, ""))
existing = sorted(existing)
vrf = stored_vrfs[network] if network in stored_vrfs else (existing[0] if existing else "")
if vrf and vrf not in vrfs:
vrfs.append(vrf) # chosen earlier as new VRF, not created yet
networks.append({"network": network, "vrf": vrf, "existing_vrfs": existing,
"create": create_prefixes is None or network in create_prefixes})
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
candidates, vlan_matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, related_id(device, "site"))
tenants = candidate_tenants(nb, tenant_id)
allowed = {row["id"] for row in tenants}
vlan_map = config.get("vlan_map") or {}
vlans = []
for vid, (record, method, new_name) in vlan_matches.items():
new_tenant = (vlan_map.get(str(vid)) or {}).get("tenant")
vlans.append({
"vid": vid, "name": names.get(vid) or f"VLAN{vid}", "method": method, "new_name": new_name,
"stored": str(vid) in vlan_map,
"new_tenant": new_tenant if new_tenant in allowed else tenant_id,
"netbox_id": record.id if record else None,
"candidates": [{"id": vlan.id, "label": vlan_choice_label(vlan)}
for vlan in sorted(candidates, key=lambda item: (item.name or "").casefold())
if vlan.vid == vid],
})
return { return {
"error": None, "error": None,
"device": {"id": device.id, "name": device.name}, "device": {"id": device.id, "name": device.name},
"interfaces": [ "interfaces": [
{"name": item["name"], "netbox_name": record.name if record else "", "method": method, {"name": item["name"], "netbox_name": record.name if record else "", "method": method,
"physical": _physical_interface(item), "vlan_label": vlan_label(item.get("vlans"))} "physical": _physical_interface(item),
"vlan_label": vlan_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
for item in snapshot["interfaces"] for item in snapshot["interfaces"]
for record, method in [matches[item["name"]]] for record, method in [matches[item["name"]]]
], ],
@@ -1066,6 +1260,11 @@ def plan_switch_sync(nb, config, snapshot):
"neighbors": neighbors, "neighbors": neighbors,
"device_scope": scope, "device_scope": scope,
"devices": devices, "devices": devices,
"tenant": getattr(getattr(device, "tenant", None), "name", None) or str(tenant_id),
"vrfs": vrfs,
"networks": networks,
"vlans": vlans,
"tenants": tenants,
} }
@@ -1119,11 +1318,107 @@ class _RemoteLookup:
return None return None
_NEW = "new" # placeholder ID of objects a dry run would create
def _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report):
"""``{network: VRF ID or None}``; VRFs chosen by name are created for the tenant."""
by_name = {vrf.name: vrf.id for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)}
chosen = config.get("network_vrfs") or {}
result = {}
for network in snapshot_networks(snapshot):
name = chosen.get(network) or ""
if name and name not in by_name:
report["vrfs_created"] += 1
report["changes"].append(f"VRF {name} neu")
by_name[name] = _NEW if dry_run else nb.ipam.vrfs.create({"name": name, "tenant": tenant_id}).id
result[network] = by_name[name] if name else None
return result
def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
"""Create missing prefixes that were approved; existing ones stay untouched."""
approved = set(config.get("create_prefixes") or [])
for network in snapshot_networks(snapshot):
vrf_id = vrf_ids.get(network)
if network not in approved:
continue
if vrf_id != _NEW and list(nb.ipam.prefixes.filter(prefix=network, vrf_id=vrf_id or "null")):
continue
try:
report["prefixes_created"] += 1
vrf_name = (config.get("network_vrfs") or {}).get(network) or "global"
report["changes"].append(f"Prefix {network} neu ({vrf_name})")
if not dry_run:
nb.ipam.prefixes.create({"prefix": network, "status": "active", "tenant": tenant_id, "vrf": vrf_id})
except Exception as error: # noqa: BLE001
report["errors"].append(f"Prefix {network}: {error}")
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved."""
_vlans, matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id)
approved = {int(vid) for vid, choice in (config.get("vlan_map") or {}).items() if choice.get("action") == "new"}
approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0
present = {}
for vid, (record, method, name) in matches.items():
if record is not None:
present[vid] = record.id
continue
if method != "new" or vid not in approved:
continue
try:
report["vlans_created"] += 1
report["changes"].append(f"VLAN {vid} „{name}“ neu")
# A different tenant may be chosen per VLAN in the review dialog.
chosen_tenant = ((config.get("vlan_map") or {}).get(str(vid)) or {}).get("tenant") or tenant_id
payload = {"vid": vid, "name": name[:64], "status": "active", "tenant": chosen_tenant}
if site_id:
payload["site"] = site_id
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
except Exception as error: # noqa: BLE001
report["errors"].append(f"VLAN {vid}: {error}")
return present
def _record_mode(record):
mode = getattr(record, "mode", None)
return getattr(mode, "value", mode) or ""
def _vlan_assignment(interface, vlan_ids, record=None):
"""802.1Q mode and VLANs of an interface; empty when ``record`` already matches."""
vlans = interface.get("vlans")
if not vlans or netbox_interface_type(interface) == "virtual":
return {}
untagged = next((vlan_ids[vid] for vid in vlans.get("untagged", []) if vid in vlan_ids), None)
tagged = sorted((vlan_ids[vid] for vid in vlans.get("tagged", []) if vid in vlan_ids), key=str)
if untagged is None and not tagged and not vlans.get("tagged_all"):
return {} # none of its VLANs exists in NetBox – leave the port alone
if vlans.get("tagged_all"):
wanted = {"mode": "tagged-all", "untagged_vlan": untagged, "tagged_vlans": []}
elif vlans.get("tagged"):
wanted = {"mode": "tagged", "untagged_vlan": untagged, "tagged_vlans": tagged}
else:
wanted = {"mode": "access", "untagged_vlan": untagged, "tagged_vlans": []}
if record is None:
return wanted
current = {
"mode": _record_mode(record),
"untagged_vlan": related_id(record, "untagged_vlan"),
"tagged_vlans": sorted((getattr(item, "id", item) for item in getattr(record, "tagged_vlans", None) or []),
key=str),
}
# NetBox validates the VLANs against the mode, so all three are sent together.
return {} if current == wanted else wanted
def _new_report(): def _new_report():
return { return {
"interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0, "interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0,
"ips_created": 0, "ips_updated": 0, "ips_unchanged": 0, "ips_created": 0, "ips_updated": 0, "ips_unchanged": 0,
"cables_created": 0, "cables_skipped": 0, "cables_created": 0, "cables_skipped": 0,
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
"changes": [], "errors": [], "changes": [], "errors": [],
} }
@@ -1137,11 +1432,16 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
""" """
report = _new_report() report = _new_report()
device, error = _resolve_device(nb, config) device, error = _resolve_device(nb, config)
if not error:
tenant_id, error = _require_tenant(device)
if error: if error:
report["errors"].append(error) report["errors"].append(error)
return report return report
device_id = device.id device_id = device.id
tenant_id = related_id(device, "tenant") vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report)
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report)
ignored = ignored_vlans(config.get("vlan_map"))
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)), matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
config.get("interface_map")) config.get("interface_map"))
records = {} records = {}
@@ -1149,7 +1449,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
for interface in snapshot["interfaces"]: for interface in snapshot["interfaces"]:
key = interface_key(interface["name"]) key = interface_key(interface["name"])
record, method = matches[interface["name"]] record, method = matches[interface["name"]]
label = vlan_label(interface.get("vlans")) port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
label = vlan_label(port["vlans"])
try: try:
if record: if record:
changes = {} changes = {}
@@ -1159,6 +1460,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
# routed ports and snapshots without configuration. # routed ports and snapshots without configuration.
if label and (getattr(record, "label", "") or "") != label: if label and (getattr(record, "label", "") or "") != label:
changes["label"] = label changes["label"] = label
changes.update(_vlan_assignment(port, vlan_ids, record))
if changes: if changes:
report["interfaces_updated"] += 1 report["interfaces_updated"] += 1
texts = [] texts = []
@@ -1166,6 +1468,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
texts.append("aktivieren" if changes["enabled"] else "deaktivieren") texts.append("aktivieren" if changes["enabled"] else "deaktivieren")
if "label" in changes: if "label" in changes:
texts.append(f"Label „{label}“") texts.append(f"Label „{label}“")
if "mode" in changes:
texts.append(f"VLAN-Modus {changes['mode']}")
target = record.name if method == "name" else f"{record.name} ({interface['name']})" target = record.name if method == "name" else f"{record.name} ({interface['name']})"
report["changes"].append(f"Interface {target}: {', '.join(texts)}") report["changes"].append(f"Interface {target}: {', '.join(texts)}")
if not dry_run: if not dry_run:
@@ -1181,6 +1485,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
} }
if label: if label:
payload["label"] = label payload["label"] = label
payload.update(_vlan_assignment(port, vlan_ids))
if interface.get("description"): if interface.get("description"):
payload["description"] = interface["description"][:200] payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1 report["interfaces_created"] += 1
@@ -1201,25 +1506,25 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
record = records[key] record = records[key]
for address in interface.get("ip_addresses", []): for address in interface.get("ip_addresses", []):
try: try:
host = str(ipaddress.ip_interface(address).ip) parsed = ipaddress.ip_interface(address)
candidates = [ vrf_id = vrf_ids.get(str(parsed.network))
item for item in nb.ipam.ip_addresses.filter(address=host) if vrf_id == _NEW:
if related_id(item, "vrf") is None candidates = [] # the VRF only exists after the real run
] else:
candidates = list(nb.ipam.ip_addresses.filter(address=str(parsed.ip), vrf_id=vrf_id or "null"))
if len(candidates) > 1: if len(candidates) > 1:
raise ValueError("mehrere globale IP-Adressen mit diesem Host gefunden") raise ValueError("mehrere IP-Adressen mit diesem Host in derselben VRF gefunden")
payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface"} payload = {"address": address, "status": "active", "assigned_object_type": "dcim.interface",
"tenant": tenant_id, "vrf": vrf_id}
if record: if record:
payload["assigned_object_id"] = record.id payload["assigned_object_id"] = record.id
if tenant_id:
payload["tenant"] = tenant_id
if candidates: if candidates:
current = candidates[0] current = candidates[0]
differs = ( differs = (
str(current.address) != address str(current.address) != address
or getattr(current, "assigned_object_type", None) != "dcim.interface" or getattr(current, "assigned_object_type", None) != "dcim.interface"
or getattr(current, "assigned_object_id", None) != payload.get("assigned_object_id") or getattr(current, "assigned_object_id", None) != payload.get("assigned_object_id")
or (tenant_id and related_id(current, "tenant") != tenant_id) or related_id(current, "tenant") != tenant_id
) )
if differs: if differs:
report["ips_updated"] += 1 report["ips_updated"] += 1
@@ -1271,6 +1576,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}], "a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}], "b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
"status": "connected", "status": "connected",
"tenant": tenant_id,
}) })
remote.cable = True # avoid a second cable from the reverse direction remote.cable = True # avoid a second cable from the reverse direction
except Exception as error: # noqa: BLE001 except Exception as error: # noqa: BLE001
+8 -1
View File
@@ -405,7 +405,9 @@ class Actions:
if not self.require_netbox_config(): if not self.require_netbox_config():
return return
by_id = {switch["id"]: switch for switch in self.state.switches} by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(dict(by_id[switch_id]), self.state.switch_snapshots[switch_id]) # VLAN decisions are shared by all switches of the profile.
vlan_map = self.state.profile.setdefault("vlan_map", {})
items = [(dict(by_id[switch_id], vlan_map=dict(vlan_map)), self.state.switch_snapshots[switch_id])
for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots] for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots]
if not items: if not items:
widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info") widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info")
@@ -429,6 +431,7 @@ class Actions:
needs_review = any( needs_review = any(
any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"]) any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"])
for entry in item["interfaces"]) or (create_cables and item["neighbors"]) for entry in item["interfaces"]) or (create_cables and item["neighbors"])
or item["networks"] or any(not vlan["stored"] and vlan["method"] in ("new", "ambiguous") for vlan in item["vlans"])
for _switch, item in reviewable) for _switch, item in reviewable)
def ask(): def ask():
@@ -439,13 +442,17 @@ class Actions:
if not dialog.exec(): if not dialog.exec():
return return
stored = {switch["id"]: switch for switch in self.state.switches} stored = {switch["id"]: switch for switch in self.state.switches}
vlan_map.clear()
vlan_map.update(dialog.vlan_map)
for switch, _snapshot in items: for switch, _snapshot in items:
choices = dialog.result.get(switch["id"]) choices = dialog.result.get(switch["id"])
if choices: if choices:
switch.update(choices) switch.update(choices)
if switch["id"] in stored: if switch["id"] in stored:
stored[switch["id"]].update(choices) stored[switch["id"]].update(choices)
switch["vlan_map"] = dict(vlan_map)
self.state.touch() self.state.touch()
self.state.switches_changed.emit() # ignored VLANs vanish from the VLAN column
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch", self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
on_success=show_preview, on_error=self._netbox_failed) on_success=show_preview, on_error=self._netbox_failed)
QTimer.singleShot(0, ask) QTimer.singleShot(0, ask)
+9 -4
View File
@@ -36,9 +36,9 @@ class ClientTargetDialog(_Dialog):
else: else:
self.role.setEditText(remembered) self.role.setEditText(remembered)
form.addRow("Geräterolle *", self.role) form.addRow("Geräterolle *", self.role)
self.tenant = SearchableComboBox("Kein Mandant") self.tenant = SearchableComboBox("Mandant wählen …")
self.tenant.set_items([("Kein Mandant", None)] + list(engine.tenants), options.get("netbox_tenant")) self.tenant.set_items(list(engine.tenants), options.get("netbox_tenant"))
form.addRow("Mandant", self.tenant) form.addRow("Mandant *", self.tenant)
self.root.addLayout(form) self.root.addLayout(form)
self.interfaces = checkbox("Netzwerkkarten, MAC- und IP-Adressen übernehmen", self.interfaces = checkbox("Netzwerkkarten, MAC- und IP-Adressen übernehmen",
options.get("sync_interfaces", True), options.get("sync_interfaces", True),
@@ -60,16 +60,21 @@ class ClientTargetDialog(_Dialog):
role_text = self.role.currentText().strip() role_text = self.role.currentText().strip()
role = self.role.valid_data() role = self.role.valid_data()
_mark_invalid(self.site, site is None) _mark_invalid(self.site, site is None)
tenant = self.tenant.valid_data()
_mark_invalid(self.role, not role_text) _mark_invalid(self.role, not role_text)
_mark_invalid(self.tenant, tenant is None)
if site is None: if site is None:
self.show_error("Bitte einen vorhandenen Standort auswählen.") self.show_error("Bitte einen vorhandenen Standort auswählen.")
return return
if not role_text: if not role_text:
self.show_error("Bitte eine Geräterolle auswählen oder einen Namen für eine neue Rolle eingeben.") self.show_error("Bitte eine Geräterolle auswählen oder einen Namen für eine neue Rolle eingeben.")
return return
if tenant is None:
self.show_error("Bitte einen Mandanten auswählen – alle Objekte in NetBox brauchen einen Mandanten.")
return
self.result = { self.result = {
"site_id": site, "role_id": role, "role_name": role_text, "site_id": site, "role_id": role, "role_name": role_text,
"tenant_id": self.tenant.valid_data(), "tenant_id": tenant,
"interfaces": self.interfaces.isChecked(), "update_existing": self.update_existing.isChecked(), "interfaces": self.interfaces.isChecked(), "update_existing": self.update_existing.isChecked(),
} }
super().accept() super().accept()
+202 -4
View File
@@ -26,7 +26,7 @@ from PySide6.QtWidgets import (
) )
from netbox_sync.core.config import known_hosts_path from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, forget_host_key from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, VLAN_METHODS, forget_host_key
from netbox_sync.core.virtualization import test_source from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
@@ -527,6 +527,10 @@ class SyncPreviewDialog(_Dialog):
(f"{totals.get('interfaces_updated', 0)} Interfaces geändert", "info"), (f"{totals.get('interfaces_updated', 0)} Interfaces geändert", "info"),
(f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen", "info"), (f"{totals.get('ips_created', 0) + totals.get('ips_updated', 0)} IP-Adressen", "info"),
] ]
for key, text in (("vrfs_created", "VRF(s) neu"), ("prefixes_created", "Prefix(e) neu"),
("vlans_created", "VLAN(s) neu")):
if totals.get(key):
items.append((f"{totals[key]} {text}", "info"))
if create_cables: if create_cables:
items.append((f"{totals.get('cables_created', 0)} Kabel", "info")) items.append((f"{totals.get('cables_created', 0)} Kabel", "info"))
errors = sum(len(report["errors"]) for _switch, report in reports) errors = sum(len(report["errors"]) for _switch, report in reports)
@@ -580,12 +584,15 @@ class SwitchMappingDialog(_Dialog):
def __init__(self, parent, plans, create_cables): def __init__(self, parent, plans, create_cables):
super().__init__(parent, "Zuordnung prüfen", super().__init__(parent, "Zuordnung prüfen",
"Schnittstellen, deren Name auf dem Switch anders lautet als in NetBox, wurden automatisch " "Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte "
"zugeordnet. Bitte prüfen und bei Bedarf korrigieren – die Auswahl wird im Profil gespeichert.", "erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.",
width=820) width=820)
self.resize(980, 660) self.resize(1120, 680)
self.plans = plans self.plans = plans
self.result = None self.result = None
# Profile-wide VLAN decisions; every switch config carries the same map.
self.previous_vlan_map = dict((plans[0][0].get("vlan_map") if plans else None) or {})
self.vlan_map = dict(self.previous_vlan_map)
tabs = QTabWidget() tabs = QTabWidget()
# Interfaces -------------------------------------------------------- # Interfaces --------------------------------------------------------
@@ -657,6 +664,85 @@ class SwitchMappingDialog(_Dialog):
found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id")) found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id"))
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)") tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
# Networks --------------------------------------------------------------
self.network_rows = []
networks = [(switch, plan, item) for switch, plan in plans for item in plan["networks"]]
if networks:
network_page = QWidget()
network_layout = QVBoxLayout(network_page)
network_layout.setContentsMargins(0, 12, 0, 0)
network_layout.addWidget(label(
"Netze der Switch-IP-Adressen. Die VRF gilt für Prefix und IP-Adressen; zur Auswahl stehen die "
"globale Tabelle und die VRFs des Mandanten. Fehlende Prefixe werden nur angelegt, wenn sie "
"angehakt sind – immer mit dem Mandanten des Switches.", muted=True, wrap=True))
self.network_table = QTableWidget(0, 5)
self.network_table.setHorizontalHeaderLabels(["Switch", "Mandant", "Netz", "VRF", "Prefix in NetBox"])
for switch, plan, item in networks:
row = self.network_table.rowCount()
self.network_table.insertRow(row)
combo = QComboBox()
combo.addItem("Global (keine VRF)", "")
for name in plan["vrfs"]:
combo.addItem(name, name)
combo.addItem("+ Neue VRF …", self.NEW)
combo.setCurrentIndex(max(0, combo.findData(item["vrf"])))
combo.setProperty("previous", combo.currentIndex())
for column, text in enumerate((switch["name"], plan["tenant"], item["network"])):
self.network_table.setItem(row, column, QTableWidgetItem(text))
self.network_table.setCellWidget(row, 3, combo)
status = QTableWidgetItem()
self.network_table.setItem(row, 4, status)
entry = (row, switch, item, combo, status)
self.network_rows.append(entry)
combo.activated.connect(lambda _index, entry=entry: self._vrf_chosen(entry))
self._update_network_row(entry, item["create"])
self._prepare_table(self.network_table, (140, 140, 150, 220, 200))
network_layout.addWidget(self.network_table, 1)
missing = sum(1 for _row, _switch, item, _combo, _status in self.network_rows if not item["existing_vrfs"])
tabs.addTab(network_page, f"Netze ({missing} Prefix(e) fehlen)")
# VLANs -----------------------------------------------------------------
# VLAN decisions apply to all switches of the profile: one row per VID.
self.vlan_rows = []
merged = {}
for switch, plan in plans:
for item in plan["vlans"]:
entry = merged.setdefault(item["vid"], {"item": item, "switches": [], "candidates": {}, "tenants": {}})
entry["switches"].append(switch["name"])
entry["candidates"].update({candidate["id"]: candidate["label"] for candidate in item["candidates"]})
entry["tenants"].update({tenant["id"]: tenant["name"] for tenant in plan["tenants"]})
if merged:
vlan_page = QWidget()
vlan_layout = QVBoxLayout(vlan_page)
vlan_layout.setContentsMargins(0, 12, 0, 0)
vlan_layout.addWidget(label(
"Gesucht wird in der Mandantengruppe über die VLAN-ID; bei mehreren Treffern entscheiden Mandant, "
"Standort und Name. Neue VLANs erhalten den eingetragenen Namen und Mandanten. Ignorierte VLANs "
"werden weder angelegt noch zugeordnet und fehlen im Label. Die Auswahl gilt für alle Switche "
"des Profils und wird gespeichert.", muted=True, wrap=True))
settled = {vid: entry["item"]["stored"] or entry["item"]["method"] in ("vid", "name")
for vid, entry in merged.items()}
open_count = sum(1 for value in settled.values() if not value)
self.open_vlan_table = self._vlan_table()
self.settled_vlan_table = self._vlan_table()
for vid in sorted(merged):
self._add_vlan_row(self.settled_vlan_table if settled[vid] else self.open_vlan_table, merged[vid])
for table in (self.open_vlan_table, self.settled_vlan_table):
self._prepare_table(table, (130, 60, 150, 280, 190, 170, 110))
vlan_layout.addWidget(label(f"<b>Zu prüfen ({open_count})</b>" if open_count else
"Alle VLANs sind zugeordnet oder gespeichert.", wrap=True))
vlan_layout.addWidget(self.open_vlan_table, 1)
self.open_vlan_table.setVisible(bool(open_count))
self.settled_toggle = button("", variant="link")
self.settled_toggle.setCheckable(True)
self.settled_toggle.toggled.connect(self._toggle_settled)
vlan_layout.addWidget(self.settled_toggle, 0, Qt.AlignLeft)
vlan_layout.addWidget(self.settled_vlan_table, 1)
self._settled_count = len(merged) - open_count
self._toggle_settled(False)
missing = sum(1 for entry in merged.values() if entry["item"]["method"] == "new")
tabs.addTab(vlan_page, f"VLANs ({open_count} zu prüfen, {missing} fehlen)")
self.root.addWidget(tabs, 1) self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner) self.root.addWidget(self.error_banner)
buttons, _ok = form_dialog_buttons(self, "Weiter zur Vorschau") buttons, _ok = form_dialog_buttons(self, "Weiter zur Vorschau")
@@ -664,6 +750,11 @@ class SwitchMappingDialog(_Dialog):
@staticmethod @staticmethod
def _prepare_table(table, widths): def _prepare_table(table, widths):
# Rows must fit the styled combo boxes, otherwise their text is clipped.
height = max((table.cellWidget(row, column).sizeHint().height()
for row in range(min(table.rowCount(), 1)) for column in range(table.columnCount())
if table.cellWidget(row, column)), default=0)
table.verticalHeader().setDefaultSectionSize(max(height + 10, table.verticalHeader().defaultSectionSize()))
table.verticalHeader().hide() table.verticalHeader().hide()
table.setEditTriggers(QTableWidget.NoEditTriggers) table.setEditTriggers(QTableWidget.NoEditTriggers)
table.setSelectionMode(QTableWidget.NoSelection) table.setSelectionMode(QTableWidget.NoSelection)
@@ -671,6 +762,90 @@ class SwitchMappingDialog(_Dialog):
for column, width in enumerate(widths): for column, width in enumerate(widths):
table.setColumnWidth(column, width) table.setColumnWidth(column, width)
IGNORE = "\x00ignore"
@staticmethod
def _vlan_table():
table = QTableWidget(0, 7)
table.setHorizontalHeaderLabels(["Switch(e)", "VLAN", "Name (Switch)", "NetBox-VLAN",
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"])
return table
def _add_vlan_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
switches = ", ".join(entry["switches"])
for column, text in enumerate((switches, str(item["vid"]), item["name"])):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
for candidate_id, text in sorted(entry["candidates"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, candidate_id)
combo.addItem("+ neu anlegen", self.NEW)
combo.addItem("– nicht zuordnen –", 0)
combo.addItem("⊘ ignorieren (auf allen Switchen)", self.IGNORE)
current = {"skip": 0, "ignore": self.IGNORE}.get(item["method"], item["netbox_id"] or self.NEW)
combo.setCurrentIndex(max(0, combo.findData(current)))
name = QLineEdit(item["new_name"])
name.setMaxLength(64)
name.setPlaceholderText(item["name"])
tenant = QComboBox()
for tenant_id, text in sorted(entry["tenants"].items(), key=lambda pair: pair[1].casefold()):
tenant.addItem(text, tenant_id)
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"])
+ (" · gespeichert" if item["stored"] else ""))
if not item["stored"] and item["method"] in ("ambiguous", "new"):
method.setForeground(QColor(theme.color("warning")))
table.setCellWidget(row, 3, combo)
table.setCellWidget(row, 4, name)
table.setCellWidget(row, 5, tenant)
table.setItem(row, 6, method)
def toggle(_index=None):
for widget in (name, tenant):
widget.setEnabled(combo.currentData() == self.NEW)
combo.currentIndexChanged.connect(toggle)
toggle()
self.vlan_rows.append((item, combo, name, tenant))
def _toggle_settled(self, expanded):
arrow = "▾" if expanded else "▸"
self.settled_toggle.setText(f"{arrow} Gespeicherte und eindeutig zugeordnete VLANs ({self._settled_count})"
+ ("" if expanded else " – zum Bearbeiten ausklappen"))
self.settled_vlan_table.setVisible(expanded and self._settled_count > 0)
self.settled_toggle.setVisible(self._settled_count > 0)
def _vrf_chosen(self, entry):
_row, switch, _item, combo, _status = entry
if combo.currentData() == self.NEW:
name = ask_text(self, "Neue VRF", "Name der neuen VRF. Sie wird beim Übertragen mit dem Mandanten "
"des Switches angelegt.")
if not name:
combo.setCurrentIndex(combo.property("previous"))
return
# Offer the new VRF in every row of the same switch.
for _r, other_switch, _i, other, _s in self.network_rows:
if other_switch["id"] == switch["id"] and other.findData(name) < 0:
other.insertItem(other.count() - 1, name, name)
combo.setCurrentIndex(combo.findData(name))
combo.setProperty("previous", combo.currentIndex())
self._update_network_row(entry)
def _update_network_row(self, entry, create=None):
_row, _switch, item, combo, status = entry
if combo.currentData() in item["existing_vrfs"]:
status.setText("vorhanden")
status.setFlags(Qt.ItemIsEnabled)
status.setData(Qt.CheckStateRole, None)
status.setForeground(QColor(theme.color("text_muted")))
return
status.setText("fehlt – anlegen")
status.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
if create is not None or status.data(Qt.CheckStateRole) is None:
status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked)
status.setForeground(QColor(theme.color("warning")))
def _filter_interfaces(self, only_unclear): def _filter_interfaces(self, only_unclear):
for row, _switch, item, _combo in self.interface_rows: for row, _switch, item, _combo in self.interface_rows:
self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name") self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name")
@@ -703,6 +878,29 @@ class SwitchMappingDialog(_Dialog):
stored.pop(neighbor["local_port"], None) stored.pop(neighbor["local_port"], None)
else: else:
stored[neighbor["local_port"]] = chosen stored[neighbor["local_port"]] = chosen
for switch, plan in self.plans:
result[switch["id"]].update({"network_vrfs": {}, "create_prefixes": [], "create_vlans": []})
for _row, switch, item, combo, status in self.network_rows:
choices = result[switch["id"]]
choices["network_vrfs"][item["network"]] = combo.currentData()
if status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked:
choices["create_prefixes"].append(item["network"])
vlan_map = dict(self.previous_vlan_map)
for item, combo, name, tenant in self.vlan_rows:
chosen = combo.currentData()
if chosen == self.NEW:
if not name.text().strip():
self.show_error(f"Bitte einen Namen für das neue VLAN {item['vid']} eingeben.")
return
choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()}
elif chosen == self.IGNORE:
choice = {"action": "ignore"}
elif chosen:
choice = {"action": "map", "id": chosen}
else:
choice = {"action": "skip"}
vlan_map[str(item["vid"])] = choice
self.vlan_map = vlan_map
self.result = result self.result = result
super().accept() super().accept()
+3 -2
View File
@@ -4,7 +4,7 @@ import uuid
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.switches import PLATFORMS, vlan_label from netbox_sync.core.switches import PLATFORMS, ignored_vlans, vlan_label, without_vlans
from netbox_sync.ui import widgets from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon from netbox_sync.ui.icons import icon
@@ -108,7 +108,8 @@ class SwitchesPage(Page):
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")), dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")), Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
sort=lambda row: row.get("speed_mbps") or 0), sort=lambda row: row.get("speed_mbps") or 0),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(row.get("vlans"))), Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans(
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))), Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))),
Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")), Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")),
Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")), Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
+1 -1
View File
@@ -74,7 +74,7 @@ class FakeNetBox:
mac_addresses=Endpoint(), platforms=Endpoint(), mac_addresses=Endpoint(), platforms=Endpoint(),
manufacturers=Endpoint(), device_types=Endpoint(), device_roles=Endpoint(), manufacturers=Endpoint(), device_types=Endpoint(), device_roles=Endpoint(),
sites=Endpoint()) sites=Endpoint())
self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint()) self.ipam = SimpleNamespace(ip_addresses=Endpoint(), prefixes=Endpoint(), vrfs=Endpoint(), vlans=Endpoint())
self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(), self.virtualization = SimpleNamespace(clusters=Endpoint(), cluster_types=Endpoint(), virtual_machines=Endpoint(),
interfaces=Endpoint()) interfaces=Endpoint())
self.tenancy = SimpleNamespace(tenants=Endpoint()) self.tenancy = SimpleNamespace(tenants=Endpoint())
+118
View File
@@ -124,3 +124,121 @@ def test_plan_offers_tenant_group_devices_and_manual_neighbor_creates_cable():
report = sync_snapshot_to_netbox(nb, switch, snapshot) report = sync_snapshot_to_netbox(nb, switch, snapshot)
cable = nb.dcim.cables.created[0] cable = nb.dcim.cables.created[0]
assert cable["a_terminations"][0]["object_id"] == 2 and cable["b_terminations"][0]["object_id"] == 20 assert cable["a_terminations"][0]["object_id"] == 2 and cable["b_terminations"][0]["object_id"] == 20
def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
nb, switch, snapshot = _numbered_setup()
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
snapshot["interfaces"][2]["vlans"] = {"untagged": [1], "tagged": [10, 20], "tagged_all": False}
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
snapshot["vlan_names"] = {20: "Clients"}
plan = plan_switch_sync(nb, switch, snapshot)
assert [(item["vid"], item["netbox_id"], item["method"], item["new_name"]) for item in plan["vlans"]] == [
(1, None, "new", "VLAN1"), (10, 110, "vid", "VLAN10"), (20, None, "new", "Clients")]
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf": "", "existing_vrfs": [], "create": True}]
# Not approved: nothing is created, only the existing VLAN 10 is assigned.
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert (report["vlans_created"], report["prefixes_created"], report["vrfs_created"]) == (0, 0, 0)
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.ipam.vlans.created == [] and nb.ipam.prefixes.created == []
assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access"
assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None
switch.update({"vlan_map": {"20": {"action": "new", "name": "Clients"}}, "create_prefixes": ["10.1.0.0/24"],
"network_vrfs": {"10.1.0.0/24": "Kunde-Mgmt"}})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.ipam.vrfs.created == [{"name": "Kunde-Mgmt", "tenant": 7}]
vrf_id = nb.ipam.vrfs.records[0].id
assert nb.ipam.prefixes.created == [{"prefix": "10.1.0.0/24", "status": "active", "tenant": 7, "vrf": vrf_id}]
assert nb.ipam.vlans.created == [{"vid": 20, "name": "Clients", "status": "active", "tenant": 7}]
port = nb.dcim.interfaces.get(3)
assert port.mode == "tagged" and sorted(port.tagged_vlans) == sorted([110, nb.ipam.vlans.records[1].id])
def test_switch_without_tenant_is_refused():
nb, switch, snapshot = _numbered_setup()
nb.dcim.devices.get(1).tenant = None
assert "keinen Mandanten" in plan_switch_sync(nb, switch, snapshot)["error"]
report = sync_snapshot_to_netbox(nb, switch, snapshot)
assert "keinen Mandanten" in report["errors"][0] and nb.dcim.interfaces.updates == []
def test_vlan_names_are_parsed():
from netbox_sync.core.switches import parse_vlan_names
assert parse_vlan_names('vlan 10\n name "Server"\n exit\nvlan 20\n name Clients\n#\n') == {
10: "Server", 20: "Clients"}
def test_vlans_of_sibling_tenants_are_matched_by_vid_and_name():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
leo = SimpleNamespace(id=8, name="Leo")
nb.ipam.vlans.records += [
Record(nb.ipam.vlans, id=201, vid=2, name="Leo Server", tenant=leo, tenant_group=group),
Record(nb.ipam.vlans, id=202, vid=2, name="Gast", tenant=SimpleNamespace(id=9), tenant_group=group),
Record(nb.ipam.vlans, id=230, vid=30, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
]
snapshot["interfaces"][0]["vlans"] = {"untagged": [2], "tagged": [], "tagged_all": False}
snapshot["vlan_names"] = {2: "Server_LEO", 30: "Drucker"}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[2]["netbox_id"], by_vid[2]["method"]) == (201, "name")
assert [candidate["id"] for candidate in by_vid[2]["candidates"]] == [202, 201]
assert by_vid[30]["method"] == "new", "VLANs outside the tenant group are never used"
switch["vlan_map"] = {"30": {"action": "new", "name": "Drucker-Netz"}, "20": {"action": "skip"}}
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.ipam.vlans.created == [{"vid": 30, "name": "Drucker-Netz", "status": "active", "tenant": 7}]
assert nb.dcim.interfaces.get(1).untagged_vlan == 201
assert getattr(nb.dcim.interfaces.get(2), "mode", None) is None, "skipped VLAN leaves the port alone"
def test_new_vlan_can_get_another_tenant_of_the_group():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=8, name="Leo", group=group))
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=9, name="Fremd", group=None))
plan = plan_switch_sync(nb, switch, snapshot)
assert [row["name"] for row in plan["tenants"]] == ["Leo", "Muster"]
assert {item["new_tenant"] for item in plan["vlans"]} == {7}
switch["vlan_map"] = {"10": {"action": "new", "name": "Leo Server", "tenant": 8}}
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.ipam.vlans.created == [{"vid": 10, "name": "Leo Server", "status": "active", "tenant": 8}]
# NetBox resolves the tenant group through the tenant; the fake needs it set.
nb.ipam.vlans.records[-1].tenant_group = group
again = plan_switch_sync(nb, switch, snapshot)["vlans"][0]
assert (again["netbox_id"], again["method"]) == (nb.ipam.vlans.records[-1].id, "manual"), "never created twice"
def test_ignored_vlans_are_left_out_everywhere():
nb, switch, snapshot = _numbered_setup()
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
snapshot["interfaces"][0]["vlans"] = {"untagged": [10], "tagged": [20, 30], "tagged_all": False}
switch["vlan_map"] = {"20": {"action": "ignore"}, "30": {"action": "new", "name": "Drucker"}}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[20]["method"], by_vid[20]["stored"]) == ("ignore", True)
assert by_vid[10]["stored"] is False
assert {item["name"]: item["vlan_label"] for item in plan["interfaces"]}["1/1/1"] == "10,30"
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert [payload["vid"] for payload in nb.ipam.vlans.created] == [30]
port = nb.dcim.interfaces.get(1)
assert port.label == "10,30" and port.tagged_vlans == [nb.ipam.vlans.records[-1].id]
def test_vlan_decisions_move_from_switches_to_the_profile(tmp_path):
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
profile = {"name": "Kunde", "switches": [{"id": "s", "name": "sw", "password": "x",
"vlan_map": {"5": {"action": "ignore"}}, "create_vlans": [6]}]}
store.save({"Kunde": profile}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["vlan_map"] == {"5": {"action": "ignore"}}
assert "vlan_map" not in loaded["switches"][0] and "create_vlans" not in loaded["switches"][0]