Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
899b4c58fc | ||
|
|
89fe37ea04 | ||
|
|
34b1391ff0 | ||
|
|
340f404f94 | ||
|
|
f1af9f8f86 | ||
|
|
2fb6ac38ec | ||
|
|
2dcd0b0855 | ||
|
|
159a933964 |
No files matched your search
@@ -49,7 +49,8 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
|||||||
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
|
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
|
||||||
|
|
||||||
- Add several NetBox devices in one step — host taken from the primary IP,
|
- Add several NetBox devices in one step — host taken from the primary IP,
|
||||||
platform suggested from model/manufacturer
|
platform suggested from model/manufacturer; members of a NetBox virtual
|
||||||
|
chassis are added once, through the chassis master
|
||||||
- Platform "detect automatically" via SSH
|
- Platform "detect automatically" via SSH
|
||||||
- Parallel SSH queries; SSH host keys are stored on first contact and verified
|
- Parallel SSH queries; SSH host keys are stored on first contact and verified
|
||||||
afterwards
|
afterwards
|
||||||
@@ -86,6 +87,10 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
|||||||
IRF): every member is assigned to its own NetBox device (suggested from the
|
IRF): every member is assigned to its own NetBox device (suggested from the
|
||||||
NetBox virtual chassis positions, stored per switch) and gets its own ports;
|
NetBox virtual chassis positions, stored per switch) and gets its own ports;
|
||||||
LAGs and VLAN interfaces stay on the switch's device
|
LAGs and VLAN interfaces stay on the switch's device
|
||||||
|
- Optional: with the [NetBox Utilities](https://git.mrblake.cc/MrBlake/Netbox-Utilities)
|
||||||
|
plugin (0.24.0 or later) a detected stack is also entered as its switch stack
|
||||||
|
(the switch's device as stack switch, the other member devices as members);
|
||||||
|
members entered by hand are kept. Without the plugin this step is skipped
|
||||||
- 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
|
||||||
@@ -95,18 +100,18 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
|||||||
- Loads the access point export of Sophos Central (comma or semicolon, UTF-8 or
|
- Loads the access point export of Sophos Central (comma or semicolon, UTF-8 or
|
||||||
Windows encoding) and checks it: missing site, duplicate IP, serial number or
|
Windows encoding) and checks it: missing site, duplicate IP, serial number or
|
||||||
MAC address
|
MAC address
|
||||||
- Finds existing APs in NetBox globally by serial number and MAC address and by
|
- No tenant to pick up front: existing APs are found in all of NetBox by serial
|
||||||
name within the tenant group; NetBox APs of the tenant group that are missing
|
number, MAC address and name; Sophos APs in NetBox that are missing in the
|
||||||
in the export are listed as "only in NetBox"
|
export are listed as "only in NetBox" for the tenants the export concerns
|
||||||
- Sophos sites are mapped to NetBox sites of the tenant group (suggested by
|
- Sophos sites are mapped to NetBox sites (suggested by name, stored per
|
||||||
name, stored per profile); the site is optional – APs without one go to a
|
profile); the site is optional – APs without one go to a default site, since
|
||||||
default site, since NetBox requires a site for every device. The tenant is
|
NetBox requires a site for every device. The tenant is mandatory and chosen
|
||||||
mandatory and can be chosen per Sophos site (default: the site's tenant)
|
deliberately per Sophos site – it is never preselected. Sophos sites left without site and tenant are
|
||||||
|
ignored (stored per profile) and not transferred
|
||||||
- New APs are created with Sophos device type, role, site, serial number,
|
- New APs are created with Sophos device type, role, site, serial number,
|
||||||
firmware, interface with MAC and IP address (primary IPv4); existing ones get
|
firmware, interface with MAC and IP address (primary IPv4); existing ones get
|
||||||
missing serial numbers and tenants, optionally the Sophos name. Tenant comes
|
missing serial numbers and tenants, optionally the Sophos name. Preview before
|
||||||
from the NetBox site, otherwise the selected tenant; devices of other tenants
|
writing
|
||||||
are never changed. Preview before writing
|
|
||||||
|
|
||||||
### Network scanner (read only)
|
### Network scanner (read only)
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
#define AppName "NetBox Synchronizer"
|
#define AppName "NetBox Synchronizer"
|
||||||
#ifndef AppVersion
|
#ifndef AppVersion
|
||||||
#define AppVersion "4.10.2"
|
#define AppVersion "4.11.0"
|
||||||
#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.10.2"
|
APP_VERSION = "4.11.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"
|
||||||
|
|
||||||
|
|||||||
@@ -129,9 +129,21 @@ class APSyncEngine(ClientSyncEngine):
|
|||||||
# Context
|
# Context
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def load_context(self, tenant_id):
|
def load_context(self, tenant_id=None):
|
||||||
"""Sites and existing Sophos devices of the tenant's tenant group."""
|
"""Sites and existing Sophos devices of the tenant's tenant group, or of all of NetBox without a tenant."""
|
||||||
self.tenant_id = tenant_id
|
self.tenant_id = tenant_id
|
||||||
|
if tenant_id is None:
|
||||||
|
tenants = {item.id: item.name for item in self.nb.tenancy.tenants.all()}
|
||||||
|
self.tenant_ids = set(tenants)
|
||||||
|
self.group_tenants = sorted(({"id": key, "name": name} for key, name in tenants.items()),
|
||||||
|
key=lambda row: row["name"].casefold())
|
||||||
|
self.ap_sites = sorted(({"id": site.id, "name": site.name, "tenant_id": related_id(site, "tenant"),
|
||||||
|
"tenant": tenants.get(related_id(site, "tenant"), "")}
|
||||||
|
for site in self.nb.dcim.sites.all()), key=lambda row: row["name"].casefold())
|
||||||
|
manufacturer = (self.nb.dcim.manufacturers.get(slug="sophos")
|
||||||
|
or next(iter(self.nb.dcim.manufacturers.filter(name__ie=MANUFACTURER)), None))
|
||||||
|
self.netbox_aps = list(self.nb.dcim.devices.filter(manufacturer_id=manufacturer.id)) if manufacturer else []
|
||||||
|
return self.ap_sites
|
||||||
tenant = self.nb.tenancy.tenants.get(tenant_id)
|
tenant = self.nb.tenancy.tenants.get(tenant_id)
|
||||||
if tenant is None:
|
if tenant is None:
|
||||||
raise APImportError(f"Mandant #{tenant_id} existiert nicht.")
|
raise APImportError(f"Mandant #{tenant_id} existiert nicht.")
|
||||||
|
|||||||
@@ -1583,6 +1583,43 @@ def _new_report():
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _sync_switch_stack(nb, device, members, dry_run, report):
|
||||||
|
"""Fill in the switch stack of the optional NetBox Utilities plugin.
|
||||||
|
|
||||||
|
The switch's device is the stack switch, the other member devices are
|
||||||
|
added to it; members entered by hand stay. Without the plugin nothing happens.
|
||||||
|
"""
|
||||||
|
others = {member.id: member for member in members.values() if member is not None and member.id != device.id}
|
||||||
|
if not others:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
endpoint = nb.plugins.utilities.switch_stacks
|
||||||
|
stacks = list(endpoint.filter(device_id=device.id))
|
||||||
|
except AttributeError:
|
||||||
|
return
|
||||||
|
except Exception as error: # noqa: BLE001
|
||||||
|
if getattr(getattr(error, "req", None), "status_code", None) != 404:
|
||||||
|
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
||||||
|
return
|
||||||
|
stack = stacks[0] if stacks else None
|
||||||
|
current = [getattr(item, "id", item) for item in (getattr(stack, "members", None) or [])]
|
||||||
|
missing = [member_id for member_id in others if member_id not in current]
|
||||||
|
if not missing:
|
||||||
|
return
|
||||||
|
names = ", ".join(others[member_id].name for member_id in missing)
|
||||||
|
report["changes"].append(f"Switch-Stack {device.name}: Mitglieder {names} eintragen (NetBox Utilities)"
|
||||||
|
if stack else f"Switch-Stack {device.name} neu mit Mitgliedern {names} (NetBox Utilities)")
|
||||||
|
if dry_run:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if stack:
|
||||||
|
stack.update({"members": current + missing})
|
||||||
|
else:
|
||||||
|
endpoint.create({"device": device.id, "members": missing})
|
||||||
|
except Exception as error: # noqa: BLE001
|
||||||
|
report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}")
|
||||||
|
|
||||||
|
|
||||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
|
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
|
||||||
"""Write a discovery snapshot to NetBox.
|
"""Write a discovery snapshot to NetBox.
|
||||||
|
|
||||||
@@ -1611,6 +1648,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
skipped = sum(1 for name, owner in owners.items() if owner is None
|
skipped = sum(1 for name, owner in owners.items() if owner is None
|
||||||
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)
|
||||||
records = {}
|
records = {}
|
||||||
|
|
||||||
for interface in snapshot["interfaces"]:
|
for interface in snapshot["interfaces"]:
|
||||||
|
|||||||
@@ -976,12 +976,14 @@ class SwitchMappingDialog(_Dialog):
|
|||||||
chosen = combo.currentData()
|
chosen = combo.currentData()
|
||||||
target = "" if chosen == self.NEW else chosen
|
target = "" if chosen == self.NEW else chosen
|
||||||
mapping = result[switch["id"]]["interface_map"]
|
mapping = result[switch["id"]]["interface_map"]
|
||||||
if target and (switch["id"], target) in used:
|
# Stack members have their own devices, so equal names are only a clash on the same device.
|
||||||
|
key = (switch["id"], item.get("owner_id"), target)
|
||||||
|
if target and key in used:
|
||||||
self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet "
|
self.show_error(f"{switch['name']}: „{target}“ ist mehreren Schnittstellen zugeordnet "
|
||||||
f"({used[(switch['id'], target)]}, {item['name']}).")
|
f"({used[key]}, {item['name']}).")
|
||||||
return
|
return
|
||||||
if target:
|
if target:
|
||||||
used[(switch["id"], target)] = item["name"]
|
used[key] = item["name"]
|
||||||
# Plain name matches stay automatic; everything else is remembered.
|
# Plain name matches stay automatic; everything else is remembered.
|
||||||
if item["method"] == "name" and target == item["netbox_name"]:
|
if item["method"] == "name" and target == item["netbox_name"]:
|
||||||
mapping.pop(item["name"], None)
|
mapping.pop(item["name"], None)
|
||||||
|
|||||||
@@ -30,8 +30,10 @@ from netbox_sync.ui.widgets import (
|
|||||||
label,
|
label,
|
||||||
)
|
)
|
||||||
|
|
||||||
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox"}
|
STATE_TEXT = {"new": "neu", "known": "in NetBox", "check": "prüfen", "netbox_only": "nur in NetBox",
|
||||||
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint"}
|
"ignored": "ignoriert"}
|
||||||
|
STATE_DOT = {"new": "accent", "known": "success", "check": "warning", "netbox_only": "text_faint",
|
||||||
|
"ignored": "text_faint"}
|
||||||
ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap")
|
ROLE_HINTS = ("access point", "accesspoint", "access-point", "wlan", "wifi", "ap")
|
||||||
|
|
||||||
|
|
||||||
@@ -46,17 +48,16 @@ class SiteMappingDialog(_Dialog):
|
|||||||
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
|
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
|
||||||
and to APs without a Sophos site."""
|
and to APs without a Sophos site."""
|
||||||
|
|
||||||
def __init__(self, parent, rows, sites, tenants, default_tenant):
|
def __init__(self, parent, rows, sites, tenants):
|
||||||
super().__init__(parent, "Standorte & Mandanten zuordnen",
|
super().__init__(parent, "Standorte & Mandanten zuordnen",
|
||||||
"Der Standort ist optional – APs ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
|
"Der Standort ist optional – APs ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
|
||||||
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht; vorgeschlagen wird der des "
|
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht und wird bewusst gewählt. Zeilen ohne "
|
||||||
"Standorts, sonst der gewählte Mandant.", width=860)
|
"Standort und ohne Mandant werden ignoriert.",
|
||||||
|
width=860)
|
||||||
self.resize(980, 620)
|
self.resize(980, 620)
|
||||||
self.sites = {site["id"]: site for site in sites}
|
|
||||||
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
|
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
|
||||||
(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
|
(site["name"] + (f" ({site['tenant']})" if site["tenant"] else ""), site["id"]) for site in sites]
|
||||||
tenant_items = [(tenant["name"], tenant["id"]) for tenant in tenants]
|
tenant_items = [(tenant["name"], tenant["id"]) for tenant in tenants]
|
||||||
self.default_tenant = default_tenant
|
|
||||||
self.table = QTableWidget(0, 4)
|
self.table = QTableWidget(0, 4)
|
||||||
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort (optional)",
|
self.table.setHorizontalHeaderLabels(["Sophos-Standort / Access Point", "APs", "NetBox-Standort (optional)",
|
||||||
"Mandant *"])
|
"Mandant *"])
|
||||||
@@ -69,9 +70,8 @@ class SiteMappingDialog(_Dialog):
|
|||||||
site = SearchableComboBox("Standort suchen …")
|
site = SearchableComboBox("Standort suchen …")
|
||||||
site.set_items(site_items, current["site"] or 0)
|
site.set_items(site_items, current["site"] or 0)
|
||||||
tenant = SearchableComboBox("Mandant wählen …")
|
tenant = SearchableComboBox("Mandant wählen …")
|
||||||
tenant.set_items(tenant_items, current["tenant"] or self._site_tenant(current["site"]))
|
# only a stored choice is shown – never a suggestion
|
||||||
site.activated.connect(lambda _index, site=site, tenant=tenant: tenant.select_data(
|
tenant.set_items(tenant_items, current["tenant"])
|
||||||
self._site_tenant(site.valid_data())))
|
|
||||||
self.table.setCellWidget(row, 2, site)
|
self.table.setCellWidget(row, 2, site)
|
||||||
self.table.setCellWidget(row, 3, tenant)
|
self.table.setCellWidget(row, 3, tenant)
|
||||||
self.rows.append((key, site, tenant))
|
self.rows.append((key, site, tenant))
|
||||||
@@ -88,13 +88,10 @@ class SiteMappingDialog(_Dialog):
|
|||||||
self.root.addWidget(buttons)
|
self.root.addWidget(buttons)
|
||||||
self.result = {}
|
self.result = {}
|
||||||
|
|
||||||
def _site_tenant(self, site_id):
|
|
||||||
return (self.sites.get(site_id) or {}).get("tenant_id") or self.default_tenant
|
|
||||||
|
|
||||||
def accept(self):
|
def accept(self):
|
||||||
result = {}
|
result = {}
|
||||||
for key, site, tenant in self.rows:
|
for key, site, tenant in self.rows:
|
||||||
if tenant.valid_data() is None:
|
if tenant.valid_data() is None and site.valid_data():
|
||||||
self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.")
|
self.show_error(f"Bitte für „{key[1]}“ einen Mandanten wählen.")
|
||||||
return
|
return
|
||||||
result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()}
|
result[key] = {"site": site.valid_data() or None, "tenant": tenant.valid_data()}
|
||||||
@@ -105,14 +102,14 @@ class SiteMappingDialog(_Dialog):
|
|||||||
class AccessPointsPage(Page):
|
class AccessPointsPage(Page):
|
||||||
title = "Access Points"
|
title = "Access Points"
|
||||||
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
|
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
|
||||||
"Seriennummer und MAC, im Mandanten über den Namen) und fehlende anlegen.")
|
"Seriennummer, MAC und Name) und fehlende anlegen.")
|
||||||
|
|
||||||
def __init__(self, window):
|
def __init__(self, window):
|
||||||
super().__init__(window)
|
super().__init__(window)
|
||||||
self.aps = []
|
self.aps = []
|
||||||
self.only_netbox = []
|
self.only_netbox = []
|
||||||
self.engine = None
|
self.engine = None
|
||||||
self.tenants = []
|
self.roles = []
|
||||||
self.file_name = ""
|
self.file_name = ""
|
||||||
|
|
||||||
source = Card("Sophos-Export", "In Sophos Central: Wireless › Access Points › Exportieren (CSV).")
|
source = Card("Sophos-Export", "In Sophos Central: Wireless › Access Points › Exportieren (CSV).")
|
||||||
@@ -121,13 +118,6 @@ class AccessPointsPage(Page):
|
|||||||
on_click=self.sync))
|
on_click=self.sync))
|
||||||
form = QFormLayout()
|
form = QFormLayout()
|
||||||
form.setHorizontalSpacing(18)
|
form.setHorizontalSpacing(18)
|
||||||
tenant_row = QHBoxLayout()
|
|
||||||
self.tenant = SearchableComboBox("Mandant wählen …")
|
|
||||||
self.tenant.setMinimumWidth(320)
|
|
||||||
tenant_row.addWidget(self.tenant)
|
|
||||||
self.tenant_hint = label("Standorte und vorhandene APs werden in seiner Mandantengruppe gesucht.", muted=True)
|
|
||||||
tenant_row.addWidget(self.tenant_hint, 1)
|
|
||||||
form.addRow("Mandant *", tenant_row)
|
|
||||||
self.role = SearchableComboBox("Geräterolle wählen …")
|
self.role = SearchableComboBox("Geräterolle wählen …")
|
||||||
self.role.setMinimumWidth(320)
|
self.role.setMinimumWidth(320)
|
||||||
form.addRow("Geräterolle", self.role)
|
form.addRow("Geräterolle", self.role)
|
||||||
@@ -192,7 +182,6 @@ class AccessPointsPage(Page):
|
|||||||
self.search.textChanged.connect(self.proxy.set_text)
|
self.search.textChanged.connect(self.proxy.set_text)
|
||||||
self.only_open.toggled.connect(lambda value: self.proxy.set_predicate(
|
self.only_open.toggled.connect(lambda value: self.proxy.set_predicate(
|
||||||
"open", (lambda row: row["state"] in ("new", "check")) if value else None))
|
"open", (lambda row: row["state"] in ("new", "check")) if value else None))
|
||||||
self.tenant.activated.connect(lambda _index: self._tenant_chosen())
|
|
||||||
self.role.activated.connect(lambda _index: self._store(role_id=self.role.valid_data()))
|
self.role.activated.connect(lambda _index: self._store(role_id=self.role.valid_data()))
|
||||||
self.default_site.activated.connect(lambda _index: (self._store(default_site=self.default_site.valid_data()),
|
self.default_site.activated.connect(lambda _index: (self._store(default_site=self.default_site.valid_data()),
|
||||||
self._refresh()))
|
self._refresh()))
|
||||||
@@ -214,8 +203,7 @@ class AccessPointsPage(Page):
|
|||||||
self.state.touch()
|
self.state.touch()
|
||||||
|
|
||||||
def _profile_switched(self):
|
def _profile_switched(self):
|
||||||
self.aps, self.only_netbox, self.engine, self.tenants = [], [], None, []
|
self.aps, self.only_netbox, self.engine, self.roles = [], [], None, []
|
||||||
self.tenant.set_items([])
|
|
||||||
self.role.set_items([])
|
self.role.set_items([])
|
||||||
self.default_site.set_items([])
|
self.default_site.set_items([])
|
||||||
self.rename.blockSignals(True)
|
self.rename.blockSignals(True)
|
||||||
@@ -224,7 +212,7 @@ class AccessPointsPage(Page):
|
|||||||
self._refresh()
|
self._refresh()
|
||||||
|
|
||||||
def on_show(self):
|
def on_show(self):
|
||||||
if not self.tenants and self._netbox_ready() and not self.tasks.busy:
|
if not self.roles and self._netbox_ready() and not self.tasks.busy:
|
||||||
self._load_lists()
|
self._load_lists()
|
||||||
|
|
||||||
def set_busy(self, busy):
|
def set_busy(self, busy):
|
||||||
@@ -261,36 +249,24 @@ class AccessPointsPage(Page):
|
|||||||
|
|
||||||
def work(ctx):
|
def work(ctx):
|
||||||
nb = connect(ctx)
|
nb = connect(ctx)
|
||||||
ctx.log("Lade Mandanten und Geräterollen …")
|
ctx.log("Lade Geräterollen …")
|
||||||
tenants = sorted(((item.name, item.id) for item in nb.tenancy.tenants.all()), key=lambda x: x[0].casefold())
|
return sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
|
||||||
roles = sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
|
|
||||||
return tenants, roles
|
|
||||||
|
|
||||||
def done(result):
|
def done(roles):
|
||||||
self.tenants, roles = result
|
self.roles = roles
|
||||||
settings = self._settings()
|
settings = self._settings()
|
||||||
# The tenant is always chosen deliberately – never preselected.
|
|
||||||
self.tenant.set_items(self.tenants)
|
|
||||||
role_id = settings.get("role_id") or next(
|
role_id = settings.get("role_id") or next(
|
||||||
(role_id for name, role_id in roles if name.casefold() in ROLE_HINTS
|
(role_id for name, role_id in roles if name.casefold() in ROLE_HINTS
|
||||||
or "access point" in name.casefold()), None)
|
or "access point" in name.casefold()), None)
|
||||||
self.role.set_items(roles, role_id)
|
self.role.set_items(roles, role_id)
|
||||||
if then_compare and self.tenant.valid_data():
|
if then_compare:
|
||||||
QTimer.singleShot(0, self.compare)
|
QTimer.singleShot(0, self.compare)
|
||||||
|
|
||||||
self.tasks.run(work, title="Mandanten laden", area="app", on_success=done,
|
self.tasks.run(work, title="Geräterollen laden", area="app", on_success=done,
|
||||||
on_error=self.actions._netbox_failed)
|
on_error=self.actions._netbox_failed)
|
||||||
|
|
||||||
def _tenant_chosen(self):
|
|
||||||
self._store(tenant_id=self.tenant.valid_data())
|
|
||||||
if self.aps and self.tenant.valid_data():
|
|
||||||
self.compare()
|
|
||||||
|
|
||||||
def compare(self):
|
def compare(self):
|
||||||
tenant_id = self.tenant.valid_data()
|
if not self.aps or self.tasks.busy:
|
||||||
if not self.aps or not tenant_id or self.tasks.busy:
|
|
||||||
if not tenant_id and self.aps:
|
|
||||||
self.window.toast("Bitte zuerst den Mandanten wählen.", "info")
|
|
||||||
return
|
return
|
||||||
connect = self.actions._connector()
|
connect = self.actions._connector()
|
||||||
aps = [dict(ap, issues=[issue for issue in ap["issues"] if not issue.startswith(("NetBox-Gerät gehört",
|
aps = [dict(ap, issues=[issue for issue in ap["issues"] if not issue.startswith(("NetBox-Gerät gehört",
|
||||||
@@ -299,8 +275,8 @@ class AccessPointsPage(Page):
|
|||||||
|
|
||||||
def work(ctx):
|
def work(ctx):
|
||||||
engine = APSyncEngine(connect(ctx), ctx.log)
|
engine = APSyncEngine(connect(ctx), ctx.log)
|
||||||
ctx.log("Lade Standorte und vorhandene Access Points der Mandantengruppe …")
|
ctx.log("Lade Standorte, Mandanten und vorhandene Sophos-Geräte …")
|
||||||
engine.load_context(tenant_id)
|
engine.load_context()
|
||||||
ctx.log(f"Suche {len(aps)} Access Points in NetBox (Seriennummer, MAC, Name) …")
|
ctx.log(f"Suche {len(aps)} Access Points in NetBox (Seriennummer, MAC, Name) …")
|
||||||
only_netbox = engine.match(aps)
|
only_netbox = engine.match(aps)
|
||||||
return engine, aps, only_netbox
|
return engine, aps, only_netbox
|
||||||
@@ -328,14 +304,14 @@ class AccessPointsPage(Page):
|
|||||||
stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
|
stored = (settings.get("ap_sites") or {}).get(ap_key(ap)) or (settings.get("site_map") or {}).get(
|
||||||
ap["site_hint"])
|
ap["site_hint"])
|
||||||
if stored:
|
if stored:
|
||||||
return dict(placement_value(stored), stored=True)
|
value = placement_value(stored)
|
||||||
|
# neither site nor tenant: the user chose to leave these APs out
|
||||||
|
return dict(value, stored=True, ignored=not value["site"] and not value["tenant"])
|
||||||
site = self.engine.suggest_site(ap["site_hint"]) if self.engine else None
|
site = self.engine.suggest_site(ap["site_hint"]) if self.engine else None
|
||||||
return {"site": site, "tenant": None, "stored": False}
|
return {"site": site, "tenant": None, "stored": False, "ignored": False}
|
||||||
|
|
||||||
def _tenant_for(self, placement):
|
def _tenant_for(self, placement):
|
||||||
if placement.get("tenant"):
|
return placement.get("tenant")
|
||||||
return placement["tenant"]
|
|
||||||
return self.engine._site_tenant(placement.get("site")) if self.engine else None
|
|
||||||
|
|
||||||
def _site_name(self, site_id):
|
def _site_name(self, site_id):
|
||||||
sites = self.engine.ap_sites if self.engine else []
|
sites = self.engine.ap_sites if self.engine else []
|
||||||
@@ -356,6 +332,8 @@ class AccessPointsPage(Page):
|
|||||||
site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site))
|
site_name = getattr(site, "name", "") or self._site_name(getattr(site, "id", site))
|
||||||
tenant_name = getattr(getattr(device, "tenant", None), "name", "") or self._tenant_name(
|
tenant_name = getattr(getattr(device, "tenant", None), "name", "") or self._tenant_name(
|
||||||
related_id(device, "tenant"))
|
related_id(device, "tenant"))
|
||||||
|
elif self.engine and self._placement(ap)["ignored"]:
|
||||||
|
site_name = ""
|
||||||
elif self.engine:
|
elif self.engine:
|
||||||
placement = self._placement(ap)
|
placement = self._placement(ap)
|
||||||
site_id = placement["site"] or default_site
|
site_id = placement["site"] or default_site
|
||||||
@@ -364,11 +342,15 @@ class AccessPointsPage(Page):
|
|||||||
tenant_name = self._tenant_name(self._tenant_for(placement))
|
tenant_name = self._tenant_name(self._tenant_for(placement))
|
||||||
else:
|
else:
|
||||||
site_name = ""
|
site_name = ""
|
||||||
state = "new" if not device else ("check" if ap["issues"] else "known")
|
state = ("ignored" if self.engine and self._placement(ap)["ignored"] else "new") if not device else ("check" if ap["issues"] else "known")
|
||||||
rows.append(dict(ap, key=ap_key(ap), state=state if self.engine else "", site_id=site_id,
|
rows.append(dict(ap, key=ap_key(ap), state=state if self.engine else "", site_id=site_id,
|
||||||
netbox_site=site_name, tenant=tenant_name or "",
|
netbox_site=site_name, tenant=tenant_name or "",
|
||||||
netbox_device=device.name if device else "", method=ap.get("method", "")))
|
netbox_device=device.name if device else "", method=ap.get("method", "")))
|
||||||
for device in self.only_netbox:
|
# NetBox APs missing in the export – only for tenants this export is about
|
||||||
|
tenants = {related_id(ap["device"], "tenant") for ap in self.aps if ap.get("device")}
|
||||||
|
tenants |= {self._tenant_for(self._placement(ap)) for ap in self.aps if not ap.get("device")}
|
||||||
|
tenants.discard(None)
|
||||||
|
for device in (device for device in self.only_netbox if related_id(device, "tenant") in tenants):
|
||||||
rows.append({"key": f"netbox-{device.id}", "state": "netbox_only", "name": device.name,
|
rows.append({"key": f"netbox-{device.id}", "state": "netbox_only", "name": device.name,
|
||||||
"model": getattr(getattr(device, "device_type", None), "model", "") or "",
|
"model": getattr(getattr(device, "device_type", None), "model", "") or "",
|
||||||
"serial": getattr(device, "serial", "") or "", "mac": "",
|
"serial": getattr(device, "serial", "") or "", "mac": "",
|
||||||
@@ -385,11 +367,13 @@ class AccessPointsPage(Page):
|
|||||||
if self.engine:
|
if self.engine:
|
||||||
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
|
parts += [f"{counts['known']} in NetBox", f"{counts['new']} neu", f"{counts['check']} zu prüfen",
|
||||||
f"{counts['netbox_only']} nur in NetBox"]
|
f"{counts['netbox_only']} nur in NetBox"]
|
||||||
|
if counts["ignored"]:
|
||||||
|
parts.append(f"{counts['ignored']} ignoriert")
|
||||||
missing_sites = sum(1 for row in rows if row["state"] == "new" and not row.get("site_id"))
|
missing_sites = sum(1 for row in rows if row["state"] == "new" and not row.get("site_id"))
|
||||||
if missing_sites:
|
if missing_sites:
|
||||||
parts.append(f"{missing_sites} ohne Standort – Standard-Standort wählen")
|
parts.append(f"{missing_sites} ohne Standort – Standard-Standort wählen")
|
||||||
elif self.aps:
|
elif self.aps:
|
||||||
parts.append("Mandant wählen, um mit NetBox abzugleichen" if self._netbox_ready()
|
parts.append("Abgleich mit NetBox läuft …" if self._netbox_ready()
|
||||||
else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)")
|
else "kein NetBox-Abgleich (kein Zugang im Profil oder Offline-Modus)")
|
||||||
self.summary.setText(" · ".join(parts) if self.aps or self.only_netbox else "")
|
self.summary.setText(" · ".join(parts) if self.aps or self.only_netbox else "")
|
||||||
self._update_buttons()
|
self._update_buttons()
|
||||||
@@ -397,7 +381,7 @@ class AccessPointsPage(Page):
|
|||||||
def _update_buttons(self):
|
def _update_buttons(self):
|
||||||
busy = self.tasks.busy
|
busy = self.tasks.busy
|
||||||
widgets.set_enabled(self.sync_button, bool(self.engine) and not busy,
|
widgets.set_enabled(self.sync_button, bool(self.engine) and not busy,
|
||||||
"Bitte Export laden und Mandanten wählen." if not self.engine else "Bitte warten …")
|
"Bitte einen Export laden." if not self.engine else "Bitte warten …")
|
||||||
widgets.set_enabled(self.sites_button, bool(self.engine) and not busy, "Erst mit NetBox abgleichen.")
|
widgets.set_enabled(self.sites_button, bool(self.engine) and not busy, "Erst mit NetBox abgleichen.")
|
||||||
widgets.set_enabled(self.refresh_button, bool(self.aps) and not busy, "Erst einen Export laden.")
|
widgets.set_enabled(self.refresh_button, bool(self.aps) and not busy, "Erst einen Export laden.")
|
||||||
|
|
||||||
@@ -423,8 +407,7 @@ class AccessPointsPage(Page):
|
|||||||
if not rows:
|
if not rows:
|
||||||
self.window.toast("Alle Access Points sind bereits in NetBox.", "info")
|
self.window.toast("Alle Access Points sind bereits in NetBox.", "info")
|
||||||
return False
|
return False
|
||||||
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants,
|
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants)
|
||||||
self.tenant.valid_data())
|
|
||||||
if not dialog.exec():
|
if not dialog.exec():
|
||||||
return False
|
return False
|
||||||
settings = self._settings()
|
settings = self._settings()
|
||||||
@@ -438,14 +421,16 @@ class AccessPointsPage(Page):
|
|||||||
def sync(self):
|
def sync(self):
|
||||||
if not self.engine or self.tasks.busy:
|
if not self.engine or self.tasks.busy:
|
||||||
return
|
return
|
||||||
new = self._new_aps()
|
new = [ap for ap in self._new_aps() if not self._placement(ap)["ignored"]]
|
||||||
role_id = self.role.valid_data()
|
role_id = self.role.valid_data()
|
||||||
if new and not role_id:
|
if new and not role_id:
|
||||||
widgets.message(self.window, "Geräterolle fehlt", "Für neue Access Points bitte eine Geräterolle wählen.",
|
widgets.message(self.window, "Geräterolle fehlt", "Für neue Access Points bitte eine Geräterolle wählen.",
|
||||||
"info")
|
"info")
|
||||||
return
|
return
|
||||||
if any(not self._placement(ap)["stored"] for ap in new) and not self.map_sites():
|
if any(not self._placement(ap)["stored"] for ap in new):
|
||||||
return
|
if not self.map_sites():
|
||||||
|
return
|
||||||
|
new = [ap for ap in new if not self._placement(ap)["ignored"]]
|
||||||
default_site = self.default_site.valid_data()
|
default_site = self.default_site.valid_data()
|
||||||
placements = {}
|
placements = {}
|
||||||
for ap in new:
|
for ap in new:
|
||||||
@@ -458,7 +443,8 @@ class AccessPointsPage(Page):
|
|||||||
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
|
"Gerät einen Standort – bitte oben einen Standard-Standort wählen.", "info",
|
||||||
"\n".join(homeless))
|
"\n".join(homeless))
|
||||||
return
|
return
|
||||||
engine, aps, rename = self.engine, list(self.aps), self.rename.isChecked()
|
engine, rename = self.engine, self.rename.isChecked()
|
||||||
|
aps = [ap for ap in self.aps if ap.get("device") or ap_key(ap) in placements]
|
||||||
|
|
||||||
def run(dry_run):
|
def run(dry_run):
|
||||||
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
|
return lambda ctx: engine.sync(aps, placements, role_id, rename, dry_run=dry_run, default_site=default_site)
|
||||||
|
|||||||
@@ -115,3 +115,16 @@ def test_site_is_optional_with_default_site_and_tenant_can_be_chosen():
|
|||||||
engine.sync(aps, {ap_key(aps[2]): {"site": None, "tenant": 8}}, role_id=30, dry_run=False, default_site=21)
|
engine.sync(aps, {ap_key(aps[2]): {"site": None, "tenant": 8}}, role_id=30, dry_run=False, default_site=21)
|
||||||
created = nb.dcim.devices.created[-1]
|
created = nb.dcim.devices.created[-1]
|
||||||
assert (created["site"], created["tenant"]) == (21, 8)
|
assert (created["site"], created["tenant"]) == (21, 8)
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_tenant_the_whole_netbox_is_searched_and_tenant_comes_from_the_choice():
|
||||||
|
nb = _netbox()
|
||||||
|
engine = APSyncEngine(nb)
|
||||||
|
engine.load_context()
|
||||||
|
assert [tenant["name"] for tenant in engine.group_tenants] == ["Kunde Kita", "Kunde RZ"]
|
||||||
|
assert len(engine.ap_sites) == 2 and len(engine.netbox_aps) == 3
|
||||||
|
aps = parse_csv(CSV)
|
||||||
|
engine.match(aps)
|
||||||
|
assert [ap["device"].id if ap["device"] else None for ap in aps] == [102, 101, None]
|
||||||
|
report = engine.sync(aps, {ap_key(aps[2]): {"site": 21, "tenant": 7}}, role_id=30, dry_run=False)
|
||||||
|
assert report["errors"] == [] and nb.dcim.devices.created[-1]["tenant"] == 7
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
from fake_netbox import FakeNetBox, Record
|
from fake_netbox import Endpoint, FakeNetBox, Record
|
||||||
|
|
||||||
from netbox_sync.core.switches import (
|
from netbox_sync.core.switches import (
|
||||||
build_snapshot,
|
build_snapshot,
|
||||||
@@ -366,6 +366,32 @@ def test_stack_members_go_to_their_own_netbox_devices():
|
|||||||
assert [(payload["device"], payload["name"]) for payload in nb.dcim.interfaces.created] == [(1, "lag1")]
|
assert [(payload["device"], payload["name"]) for payload in nb.dcim.interfaces.created] == [(1, "lag1")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_stack_is_filled_in_netbox_utilities_when_the_plugin_exists():
|
||||||
|
nb, switch, _snapshot = _numbered_setup()
|
||||||
|
snapshot = _stack_snapshot()
|
||||||
|
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=4, name="access-01-2", tenant=SimpleNamespace(id=7)))
|
||||||
|
switch["stack_devices"] = {"1": 1, "2": 4}
|
||||||
|
# Without the plugin the stack is simply not written.
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||||
|
assert not report["errors"] and not any("Switch-Stack" in change for change in report["changes"])
|
||||||
|
|
||||||
|
nb.plugins = SimpleNamespace(utilities=SimpleNamespace(switch_stacks=Endpoint()))
|
||||||
|
stacks = nb.plugins.utilities.switch_stacks
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||||
|
assert "Switch-Stack access-01 neu mit Mitgliedern access-01-2 (NetBox Utilities)" in report["changes"]
|
||||||
|
assert stacks.created == []
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||||
|
assert stacks.created == [{"device": 1, "members": [4]}]
|
||||||
|
stacks.records[0].device = SimpleNamespace(id=1)
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||||
|
assert not any("Switch-Stack" in change for change in report["changes"]), "already complete"
|
||||||
|
|
||||||
|
# Members entered by hand stay, missing ones are added.
|
||||||
|
stacks.records[0].members = [9]
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||||
|
assert stacks.updates[-1] == (stacks.records[0].id, {"members": [9, 4]})
|
||||||
|
|
||||||
|
|
||||||
def test_virtual_chassis_positions_are_suggested():
|
def test_virtual_chassis_positions_are_suggested():
|
||||||
nb, switch, _snapshot = _numbered_setup()
|
nb, switch, _snapshot = _numbered_setup()
|
||||||
snapshot = _stack_snapshot()
|
snapshot = _stack_snapshot()
|
||||||
|
|||||||
Reference in new issue
Block a user