Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1949f03bae | ||
|
|
dfe985bb9e |
No files matched your search
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
#define AppName "NetBox Synchronizer"
|
#define AppName "NetBox Synchronizer"
|
||||||
#ifndef AppVersion
|
#ifndef AppVersion
|
||||||
#define AppVersion "4.14.0"
|
#define AppVersion "4.14.1"
|
||||||
#endif
|
#endif
|
||||||
#define AppPublisher "Louis-Alexander Kerst"
|
#define AppPublisher "Louis-Alexander Kerst"
|
||||||
#define AppExeName "NetBoxSynchronizer.exe"
|
#define AppExeName "NetBoxSynchronizer.exe"
|
||||||
|
|||||||
@@ -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.14.0"
|
APP_VERSION = "4.14.1"
|
||||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||||
|
|
||||||
|
|||||||
@@ -1571,8 +1571,12 @@ def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
|
|||||||
report["errors"].append(f"Prefix {network}: {error}")
|
report["errors"].append(f"Prefix {network}: {error}")
|
||||||
|
|
||||||
|
|
||||||
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report, sites=None):
|
||||||
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved."""
|
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved.
|
||||||
|
|
||||||
|
``sites`` receives ``{VLAN ID: (site ID or None, name)}`` for the site check of the ports.
|
||||||
|
"""
|
||||||
|
sites = {} if sites is None else sites
|
||||||
_vlans, matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id)
|
_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, 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
|
approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0
|
||||||
@@ -1580,6 +1584,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
|||||||
for vid, (record, method, name) in matches.items():
|
for vid, (record, method, name) in matches.items():
|
||||||
if record is not None:
|
if record is not None:
|
||||||
present[vid] = record.id
|
present[vid] = record.id
|
||||||
|
sites[vid] = (related_id(record, "site"), getattr(record, "name", "") or str(vid))
|
||||||
continue
|
continue
|
||||||
if method != "new" or vid not in approved:
|
if method != "new" or vid not in approved:
|
||||||
continue
|
continue
|
||||||
@@ -1592,6 +1597,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
|
|||||||
if site_id:
|
if site_id:
|
||||||
payload["site"] = site_id
|
payload["site"] = site_id
|
||||||
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
|
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
|
||||||
|
sites[vid] = (site_id, name)
|
||||||
except Exception as error: # noqa: BLE001
|
except Exception as error: # noqa: BLE001
|
||||||
report["errors"].append(f"VLAN {vid}: {error}")
|
report["errors"].append(f"VLAN {vid}: {error}")
|
||||||
return present
|
return present
|
||||||
@@ -1676,6 +1682,24 @@ def _sync_switch_stack(nb, device, members, dry_run, report):
|
|||||||
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
||||||
|
|
||||||
|
|
||||||
|
def _vlans_for_site(vlan_ids, vlan_sites, site_id, owner, reported, report):
|
||||||
|
"""VLANs a port of ``owner`` may use: NetBox only allows global VLANs or VLANs of the device's site.
|
||||||
|
|
||||||
|
Other VLANs stay in the label; each is reported once per device.
|
||||||
|
"""
|
||||||
|
allowed = {}
|
||||||
|
for vid, netbox_id in vlan_ids.items():
|
||||||
|
vlan_site, name = vlan_sites.get(vid, (None, str(vid)))
|
||||||
|
if vlan_site in (None, site_id):
|
||||||
|
allowed[vid] = netbox_id
|
||||||
|
elif (owner.id, vid) not in reported:
|
||||||
|
reported.add((owner.id, vid))
|
||||||
|
report["notes"].append(f"VLAN {vid} „{name}“ gehört zu einem anderen Standort als {owner.name} – "
|
||||||
|
f"nur im Label vermerkt, nicht am Port zugewiesen (VLAN global machen, "
|
||||||
|
f"um es zuzuweisen)")
|
||||||
|
return allowed
|
||||||
|
|
||||||
|
|
||||||
def _sync_lag_members(snapshot, owners, records, dry_run, report):
|
def _sync_lag_members(snapshot, owners, records, dry_run, report):
|
||||||
"""Assign member ports to their LAG interface (NetBox field ``lag``)."""
|
"""Assign member ports to their LAG interface (NetBox field ``lag``)."""
|
||||||
names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]}
|
names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]}
|
||||||
@@ -1811,7 +1835,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
device_id = device.id
|
device_id = device.id
|
||||||
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
|
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
|
||||||
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, 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)
|
vlan_sites = {}
|
||||||
|
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report, vlan_sites)
|
||||||
ignored = ignored_vlans(config.get("vlan_map"))
|
ignored = ignored_vlans(config.get("vlan_map"))
|
||||||
members = stack_devices(nb, config, snapshot, device)
|
members = stack_devices(nb, config, snapshot, device)
|
||||||
owners = _interface_owners(snapshot, members, device)
|
owners = _interface_owners(snapshot, members, device)
|
||||||
@@ -1823,7 +1848,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
and stack_member(name, snapshot.get("platform")) == member)
|
and stack_member(name, snapshot.get("platform")) == member)
|
||||||
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
|
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
|
||||||
_sync_switch_stack(nb, device, members, dry_run, report)
|
_sync_switch_stack(nb, device, members, dry_run, report)
|
||||||
records = {}
|
records, foreign = {}, set()
|
||||||
|
|
||||||
for interface in snapshot["interfaces"]:
|
for interface in snapshot["interfaces"]:
|
||||||
key = interface_key(interface["name"])
|
key = interface_key(interface["name"])
|
||||||
@@ -1834,6 +1859,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
where = f" auf {owner.name}" if owner.id != device_id else ""
|
where = f" auf {owner.name}" if owner.id != device_id else ""
|
||||||
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
|
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
|
||||||
label = port_label(port["vlans"], interface.get("lag"))
|
label = port_label(port["vlans"], interface.get("lag"))
|
||||||
|
owner_vlans = _vlans_for_site(vlan_ids, vlan_sites, related_id(owner, "site"), owner, foreign, report)
|
||||||
try:
|
try:
|
||||||
if record:
|
if record:
|
||||||
changes = {}
|
changes = {}
|
||||||
@@ -1843,7 +1869,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))
|
changes.update(_vlan_assignment(port, owner_vlans, record))
|
||||||
if changes:
|
if changes:
|
||||||
report["interfaces_updated"] += 1
|
report["interfaces_updated"] += 1
|
||||||
texts = []
|
texts = []
|
||||||
@@ -1868,7 +1894,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))
|
payload.update(_vlan_assignment(port, owner_vlans))
|
||||||
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
|
||||||
|
|||||||
@@ -530,6 +530,8 @@ class Actions:
|
|||||||
update_cables=update_cables)
|
update_cables=update_cables)
|
||||||
for error in report["errors"]:
|
for error in report["errors"]:
|
||||||
ctx.log(f"{switch['name']}: {error}", "error")
|
ctx.log(f"{switch['name']}: {error}", "error")
|
||||||
|
for note in report.get("notes", []):
|
||||||
|
ctx.log(f"{switch['name']}: {note}", "warning")
|
||||||
reports.append((switch, report))
|
reports.append((switch, report))
|
||||||
return reports
|
return reports
|
||||||
|
|
||||||
|
|||||||
@@ -551,6 +551,9 @@ class SyncPreviewDialog(_Dialog):
|
|||||||
errors = sum(len(report["errors"]) for _switch, report in reports)
|
errors = sum(len(report["errors"]) for _switch, report in reports)
|
||||||
if errors:
|
if errors:
|
||||||
items.append((f"{errors} Probleme", "error"))
|
items.append((f"{errors} Probleme", "error"))
|
||||||
|
notes = sum(len(report.get("notes", [])) for _switch, report in reports)
|
||||||
|
if notes:
|
||||||
|
items.append((f"{notes} Hinweis(e)", "warning"))
|
||||||
for text, kind in items:
|
for text, kind in items:
|
||||||
summary.addWidget(Badge(text, kind))
|
summary.addWidget(Badge(text, kind))
|
||||||
summary.addStretch(1)
|
summary.addStretch(1)
|
||||||
@@ -566,7 +569,9 @@ class SyncPreviewDialog(_Dialog):
|
|||||||
changes = report["changes"]
|
changes = report["changes"]
|
||||||
total_changes += len(changes)
|
total_changes += len(changes)
|
||||||
unchanged = report["interfaces_unchanged"]
|
unchanged = report["interfaces_unchanged"]
|
||||||
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"])
|
hints = len(report.get("notes", []))
|
||||||
|
top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"
|
||||||
|
+ (f", {hints} Hinweis(e)" if hints else "")])
|
||||||
top.setIcon(0, icon("network", theme.color("accent")))
|
top.setIcon(0, icon("network", theme.color("accent")))
|
||||||
font = top.font(0)
|
font = top.font(0)
|
||||||
font.setBold(True)
|
font.setBold(True)
|
||||||
@@ -595,7 +600,7 @@ class SyncPreviewDialog(_Dialog):
|
|||||||
top.addChild(member)
|
top.addChild(member)
|
||||||
member.setExpanded(True)
|
member.setExpanded(True)
|
||||||
tree.addTopLevelItem(top)
|
tree.addTopLevelItem(top)
|
||||||
top.setExpanded(len(reports) == 1 or bool(report["errors"]))
|
top.setExpanded(len(reports) == 1 or bool(report["errors"]) or bool(hints))
|
||||||
self.root.addWidget(tree, 1)
|
self.root.addWidget(tree, 1)
|
||||||
if total_changes == 0:
|
if total_changes == 0:
|
||||||
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
|
self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success"))
|
||||||
|
|||||||
@@ -596,3 +596,19 @@ def test_cables_to_patch_panels_and_busy_far_ends_are_kept():
|
|||||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||||
assert nb.dcim.cables.updates == []
|
assert nb.dcim.cables.updates == []
|
||||||
assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"])
|
assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_vlans_of_another_site_are_only_labelled():
|
||||||
|
nb, switch, snapshot = _numbered_setup()
|
||||||
|
nb.dcim.devices.get(1).site = SimpleNamespace(id=2)
|
||||||
|
nb.ipam.vlans.records += [
|
||||||
|
Record(nb.ipam.vlans, id=110, vid=10, name="MOBILE", tenant=SimpleNamespace(id=7), site=SimpleNamespace(id=1)),
|
||||||
|
Record(nb.ipam.vlans, id=120, vid=20, name="CLIENTS", tenant=SimpleNamespace(id=7), site=None),
|
||||||
|
]
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||||
|
assert report["errors"] == []
|
||||||
|
assert nb.dcim.interfaces.get(1).label == "10" and getattr(nb.dcim.interfaces.get(1), "untagged_vlan", None) is None
|
||||||
|
assert nb.dcim.interfaces.get(2).untagged_vlan == 120, "global VLANs are always assigned"
|
||||||
|
assert [note for note in report["notes"] if "VLAN 10" in note] == [
|
||||||
|
"VLAN 10 „MOBILE“ gehört zu einem anderen Standort als access-01 – nur im Label vermerkt, nicht am Port "
|
||||||
|
"zugewiesen (VLAN global machen, um es zuzuweisen)"]
|
||||||
Reference in new issue
Block a user