Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1949f03bae | ||
|
|
dfe985bb9e | ||
|
|
d853f08445 | ||
|
|
f4c507de6c | ||
|
|
3c8bc7879c | ||
|
|
770edc4a03 | ||
|
|
eee60d26ad | ||
|
|
63fd7b987a | ||
|
|
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
|
||||||
@@ -61,6 +62,12 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
|||||||
- VLAN membership per port (untagged and tagged, read from the running
|
- VLAN membership per port (untagged and tagged, read from the running
|
||||||
configuration) is written to the interface **label**, e.g. `10` or `1,20-22`;
|
configuration) is written to the interface **label**, e.g. `10` or `1,20-22`;
|
||||||
only VLAN-related lines of the configuration are kept in the raw data
|
only VLAN-related lines of the configuration are kept in the raw data
|
||||||
|
- LAG members (Aruba CX `lag N`, ArubaOS-Switch `trunk … trkN`, Comware
|
||||||
|
`port link-aggregation group N`) get their LAG in the label, e.g.
|
||||||
|
`10,20 (LAG 1)`, and are assigned to the LAG interface in NetBox (field
|
||||||
|
*LAG*; only on the same device). Members without own VLAN configuration take
|
||||||
|
the VLANs of their LAG. NetBox Utilities 0.25.0 or later ignores the LAG note
|
||||||
|
when it evaluates VLAN labels
|
||||||
- Automatic port mapping when NetBox names differ from the switch (e.g. `5` ↔
|
- Automatic port mapping when NetBox names differ from the switch (e.g. `5` ↔
|
||||||
`1/1/5`): equal name, then equal port number, then natural order
|
`1/1/5`): equal name, then equal port number, then natural order
|
||||||
- **Mapping review** before the preview: non-obvious port mappings and every
|
- **Mapping review** before the preview: non-obvious port mappings and every
|
||||||
@@ -86,7 +93,26 @@ 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
|
||||||
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
|
- 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
|
||||||
|
- Optional configuration backup ("Konfiguration als Anhang sichern"): with the
|
||||||
|
[netbox-attachments](https://github.com/Kani999/netbox-attachments) plugin the
|
||||||
|
running configuration is attached to the switch's device as a text file.
|
||||||
|
Passwords, keys and SNMP communities are removed first; a new attachment is
|
||||||
|
only added when the configuration changed (SHA-256 in the description).
|
||||||
|
Older plugin versions (parent on the attachment) and newer ones (separate
|
||||||
|
assignments) are supported; without the plugin the step is skipped with a note
|
||||||
|
- Cables from LLDP/CDP, also with FQDN system names or via the management IP.
|
||||||
|
Neighbors that report their MAC address as port ID (e.g. access points) are
|
||||||
|
matched by MAC, and a device with a single physical port is cabled there
|
||||||
|
- Existing cables are checked against LLDP/CDP: a different far end is reported
|
||||||
|
as a note. Only with the optional "Bestehende Kabel anpassen" (confirmed with
|
||||||
|
a warning, NetBox is the source of truth) the cable is moved to the reported
|
||||||
|
neighbor; such changes are marked with ⚠ in the preview. Cables to patch
|
||||||
|
panels (front/rear ports) and far ends that already have another cable are
|
||||||
|
never changed
|
||||||
- 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 +121,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.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.10.2"
|
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"
|
||||||
|
|
||||||
|
|||||||
@@ -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.")
|
||||||
|
|||||||
+263
-17
@@ -1,5 +1,7 @@
|
|||||||
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
|
"""SSH discovery and NetBox synchronization for HPE and Aruba switches."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import re
|
import re
|
||||||
import threading
|
import threading
|
||||||
@@ -8,7 +10,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
import paramiko
|
import paramiko
|
||||||
|
|
||||||
from netbox_sync.core.netbox import assign_mac, related_id
|
from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id
|
||||||
|
|
||||||
PLATFORMS = {
|
PLATFORMS = {
|
||||||
"auto": "Automatisch erkennen",
|
"auto": "Automatisch erkennen",
|
||||||
@@ -608,8 +610,8 @@ def _parse_neighbor_table(output):
|
|||||||
# VLAN membership from the running configuration
|
# VLAN membership from the running configuration
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
|
|
||||||
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*)(\d+)-(?:\1)?(\d+)$")
|
_PORT_RANGE = re.compile(r"^(\D*(?:\d+/)*[A-Za-z]?)(\d+)-(?:\1)?(\d+)$")
|
||||||
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode")
|
_VLAN_CONFIG_LINE = re.compile(r"(?i)^\s*(?:interface\s|vlan\s|#|exit|\s*(?:no\s+)?routing\b)|vlan|tagged|link-type|link-mode|^\s*lag \d|^trunk\s|link-aggregation")
|
||||||
|
|
||||||
|
|
||||||
def parse_vlan_list(text):
|
def parse_vlan_list(text):
|
||||||
@@ -776,6 +778,44 @@ def vlan_label(vlans, limit=64):
|
|||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def port_label(vlans, lag=None, limit=64):
|
||||||
|
"""NetBox label of a port: its VLANs plus its LAG, e.g. ``10,20 (LAG 1)``."""
|
||||||
|
number = re.search(r"(\d+)$", lag or "")
|
||||||
|
suffix = f"(LAG {number.group(1)})" if number else ""
|
||||||
|
text = vlan_label(vlans, limit - len(suffix) - 1 if suffix else limit)
|
||||||
|
return f"{text} {suffix}".strip()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_lags(config, platform):
|
||||||
|
"""LAG of every member port as ``{interface_key(port): LAG name}``."""
|
||||||
|
lags = {}
|
||||||
|
if platform == "aruba_aos":
|
||||||
|
# "trunk 49-50 trk1 lacp" is a global line.
|
||||||
|
for match in re.finditer(r"(?im)^trunk\s+(\S+)\s+trk(\d+)\b", clean_output(config or "")):
|
||||||
|
for port in _expand_ports(match.group(1)):
|
||||||
|
lags[interface_key(port)] = f"Trk{match.group(2)}"
|
||||||
|
return lags
|
||||||
|
member = {"aruba_cx": (re.compile(r"(?i)^lag (\d+)$"), "lag{}"),
|
||||||
|
"hpe_comware": (re.compile(r"(?i)^port link-aggregation group (\d+)$"), "Bridge-Aggregation{}")}
|
||||||
|
if platform not in member:
|
||||||
|
return lags
|
||||||
|
pattern, name = member[platform]
|
||||||
|
for match, body in _config_blocks(config or "", re.compile(r"^interface\s+(\S+)\s*$", re.I)):
|
||||||
|
group = next((found.group(1) for found in map(pattern.match, body) if found), None)
|
||||||
|
if group:
|
||||||
|
lags[interface_key(match.group(1))] = name.format(group)
|
||||||
|
return lags
|
||||||
|
|
||||||
|
|
||||||
|
# Values after these words are removed from configuration backups.
|
||||||
|
_SECRET = re.compile(r"(?i)\b(password|secret|key|community|ciphertext|plaintext|psk|passphrase)\b(\s+).*$")
|
||||||
|
|
||||||
|
|
||||||
|
def mask_config(config):
|
||||||
|
"""Running configuration without passwords, keys and SNMP communities."""
|
||||||
|
return "\n".join(_SECRET.sub(r"\1\2<entfernt>", line) for line in clean_output(config).splitlines()).strip()
|
||||||
|
|
||||||
|
|
||||||
def _vlan_config_excerpt(config):
|
def _vlan_config_excerpt(config):
|
||||||
"""Keep only VLAN-related lines – the full configuration may contain secrets."""
|
"""Keep only VLAN-related lines – the full configuration may contain secrets."""
|
||||||
return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
|
return "\n".join(line for line in clean_output(config).splitlines() if _VLAN_CONFIG_LINE.search(line))
|
||||||
@@ -826,8 +866,13 @@ def parse_stack(config, platform, interfaces=()):
|
|||||||
def build_snapshot(outputs, platform):
|
def build_snapshot(outputs, platform):
|
||||||
interfaces = parse_interfaces(outputs["interfaces"], platform)
|
interfaces = parse_interfaces(outputs["interfaces"], platform)
|
||||||
vlans = parse_vlans(outputs.get("config", ""), platform)
|
vlans = parse_vlans(outputs.get("config", ""), platform)
|
||||||
|
lags = parse_lags(outputs.get("config", ""), platform)
|
||||||
for interface in interfaces:
|
for interface in interfaces:
|
||||||
interface["vlans"] = vlans.get(interface_key(interface["name"]))
|
interface["vlans"] = vlans.get(interface_key(interface["name"]))
|
||||||
|
interface["lag"] = lags.get(interface_key(interface["name"]))
|
||||||
|
if interface["lag"] and not interface["vlans"]:
|
||||||
|
# Aruba CX/Comware: the VLANs are configured on the LAG and apply to its member ports.
|
||||||
|
interface["vlans"] = vlans.get(interface_key(interface["lag"]))
|
||||||
interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
|
interface_ips = parse_interface_ips(outputs.get("ipv4_interfaces", ""), outputs.get("ipv6_interfaces", ""), platform)
|
||||||
lldp_neighbors = parse_neighbors(outputs["neighbors"])
|
lldp_neighbors = parse_neighbors(outputs["neighbors"])
|
||||||
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
|
cdp_neighbors = parse_cdp_neighbors(outputs.get("cdp_neighbors", ""))
|
||||||
@@ -863,6 +908,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")),
|
||||||
|
"config_backup": mask_config(outputs["config"]) if outputs.get("config") else "",
|
||||||
"vlan_names": parse_vlan_names(outputs.get("config", "")),
|
"vlan_names": parse_vlan_names(outputs.get("config", "")),
|
||||||
"stack": parse_stack(outputs.get("config", ""), platform, interfaces),
|
"stack": parse_stack(outputs.get("config", ""), platform, interfaces),
|
||||||
"lldp_disabled": outputs.get("lldp_disabled", False),
|
"lldp_disabled": outputs.get("lldp_disabled", False),
|
||||||
@@ -1357,7 +1403,7 @@ def plan_switch_sync(nb, config, snapshot):
|
|||||||
"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), "owner_id": owners[item["name"]].id,
|
"physical": _physical_interface(item), "owner_id": owners[item["name"]].id,
|
||||||
"vlan_label": vlan_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
|
"vlan_label": port_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)), item.get("lag"))}
|
||||||
for item in snapshot["interfaces"] if owners[item["name"]] is not None
|
for item in snapshot["interfaces"] if owners[item["name"]] is not None
|
||||||
for record, method in [matches[item["name"]]]
|
for record, method in [matches[item["name"]]]
|
||||||
],
|
],
|
||||||
@@ -1428,7 +1474,17 @@ class _RemoteLookup:
|
|||||||
if _physical_record(record) and _port_number(record.name) == number]
|
if _physical_record(record) and _port_number(record.name) == number]
|
||||||
if len(found) == 1:
|
if len(found) == 1:
|
||||||
return found[0]
|
return found[0]
|
||||||
return None
|
# Access points and phones often report their MAC address as port ID.
|
||||||
|
mac = normalize_mac(neighbor.get("remote_port"))
|
||||||
|
if mac:
|
||||||
|
found = [record for record in records.values()
|
||||||
|
if normalize_mac(getattr(record, "mac_address", None)) == mac]
|
||||||
|
if len(found) == 1:
|
||||||
|
return found[0]
|
||||||
|
# An end device with a single port (e.g. an AP from the Sophos import) can only be cabled there.
|
||||||
|
physical = [record for record in records.values()
|
||||||
|
if _physical_record(record) and not getattr(record, "mgmt_only", False)]
|
||||||
|
return physical[0] if len(physical) == 1 else None
|
||||||
|
|
||||||
|
|
||||||
_NEW = "new" # placeholder ID of objects a dry run would create
|
_NEW = "new" # placeholder ID of objects a dry run would create
|
||||||
@@ -1515,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
|
||||||
@@ -1524,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
|
||||||
@@ -1536,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
|
||||||
@@ -1577,13 +1639,186 @@ 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_updated": 0, "cables_skipped": 0,
|
||||||
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
|
"vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0,
|
||||||
"changes": [], "errors": [], "notes": [],
|
"changes": [], "errors": [], "notes": [],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop):
|
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 _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):
|
||||||
|
"""Assign member ports to their LAG interface (NetBox field ``lag``)."""
|
||||||
|
names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]}
|
||||||
|
for interface in snapshot["interfaces"]:
|
||||||
|
key, lag_key = interface_key(interface["name"]), interface_key(interface.get("lag") or "")
|
||||||
|
if not interface.get("lag") or key not in records or lag_key not in records:
|
||||||
|
continue
|
||||||
|
record, lag_record = records[key], records[lag_key]
|
||||||
|
owner, lag_owner = owners[interface["name"]], owners[names[lag_key]]
|
||||||
|
if owner.id != lag_owner.id:
|
||||||
|
# NetBox only allows a LAG of the same device (or virtual chassis).
|
||||||
|
report["notes"].append(f"Interface {interface['name']}: LAG {names[lag_key]} liegt auf {lag_owner.name} "
|
||||||
|
f"– nur im Label vermerkt")
|
||||||
|
continue
|
||||||
|
if record and lag_record and related_id(record, "lag") == lag_record.id:
|
||||||
|
continue
|
||||||
|
report["changes"].append(f"Interface {record.name if record else interface['name']}: LAG {names[lag_key]}")
|
||||||
|
if not dry_run and record and lag_record:
|
||||||
|
try:
|
||||||
|
record.update({"lag": lag_record.id})
|
||||||
|
except Exception as error: # noqa: BLE001
|
||||||
|
report["errors"].append(f"Interface {interface['name']}: LAG {names[lag_key]}: {error}")
|
||||||
|
|
||||||
|
|
||||||
|
def _backup_config(nb, device, snapshot, dry_run, report):
|
||||||
|
"""Attach the running configuration to the device (optional netbox-attachments plugin).
|
||||||
|
|
||||||
|
A new attachment is only added when the configuration of this device changed
|
||||||
|
since the last backup; the hash in the description identifies it.
|
||||||
|
"""
|
||||||
|
config = snapshot.get("config_backup")
|
||||||
|
if not config:
|
||||||
|
report["notes"].append("Konfigurations-Backup: keine Konfiguration ausgelesen")
|
||||||
|
return
|
||||||
|
digest = hashlib.sha256(f"{device.id}\n{config}".encode("utf-8")).hexdigest()[:16]
|
||||||
|
try:
|
||||||
|
app = nb.plugins.netbox_attachments
|
||||||
|
known = [item for item in app.netbox_attachments.filter(q=digest)
|
||||||
|
if digest in (getattr(item, "description", "") or "")]
|
||||||
|
except AttributeError:
|
||||||
|
return
|
||||||
|
except Exception as error: # noqa: BLE001
|
||||||
|
if getattr(getattr(error, "req", None), "status_code", None) == 404:
|
||||||
|
report["notes"].append("Konfigurations-Backup übersprungen: Plugin netbox-attachments ist nicht installiert")
|
||||||
|
else:
|
||||||
|
report["errors"].append(f"Konfigurations-Backup: {error}")
|
||||||
|
return
|
||||||
|
if known:
|
||||||
|
return
|
||||||
|
stamp = time.strftime("%Y-%m-%d %H-%M", time.localtime(snapshot.get("discovered_at") or time.time()))
|
||||||
|
name = f"Running-Config {device.name} {stamp}"
|
||||||
|
report["changes"].append(f"Konfigurations-Backup: Anhang „{name}“")
|
||||||
|
if dry_run:
|
||||||
|
return
|
||||||
|
filename = re.sub(r"[^\w.-]+", "_", f"{device.name}_{stamp}") + ".txt"
|
||||||
|
try:
|
||||||
|
attachment = app.netbox_attachments.create({
|
||||||
|
"name": name, "description": f"Running-Config, SHA-256 {digest}",
|
||||||
|
# Older plugin versions keep the parent on the attachment itself.
|
||||||
|
"object_type": "dcim.device", "object_id": device.id,
|
||||||
|
"file": (filename, io.BytesIO(config.encode("utf-8")), "text/plain"),
|
||||||
|
})
|
||||||
|
if hasattr(attachment, "assignments"):
|
||||||
|
# Newer plugin versions assign attachments to objects separately.
|
||||||
|
app.netbox_attachment_assignments.create({"attachment": attachment.id, "object_type": "dcim.device",
|
||||||
|
"object_id": device.id})
|
||||||
|
except Exception as error: # noqa: BLE001
|
||||||
|
report["errors"].append(f"Konfigurations-Backup: {error}")
|
||||||
|
|
||||||
|
|
||||||
|
def _term(value, key):
|
||||||
|
return value.get(key) if isinstance(value, dict) else getattr(value, key, None)
|
||||||
|
|
||||||
|
|
||||||
|
def _termination_text(termination):
|
||||||
|
item = _term(termination, "object") or {}
|
||||||
|
owner = _term(_term(item, "device") or {}, "name")
|
||||||
|
return f"{owner} {_term(item, 'name')}" if owner else str(_term(item, "name") or _term(termination, "object_id"))
|
||||||
|
|
||||||
|
|
||||||
|
def _check_cable(nb, local, remote, label, update_cables, dry_run, report):
|
||||||
|
"""Compare an existing cable of a switch port with its LLDP/CDP neighbor.
|
||||||
|
|
||||||
|
NetBox is the source of truth: a different far end is only reported unless
|
||||||
|
``update_cables`` is set. Cables to patch panels (front/rear ports) or with
|
||||||
|
several terminations are never touched.
|
||||||
|
"""
|
||||||
|
cable = nb.dcim.cables.get(related_id(local, "cable"))
|
||||||
|
if cable is None:
|
||||||
|
report["cables_skipped"] += 1
|
||||||
|
return
|
||||||
|
sides = [list(_term(cable, "a_terminations") or []), list(_term(cable, "b_terminations") or [])]
|
||||||
|
local_side = next((side for side in sides if any(_term(item, "object_id") == local.id for item in side)), None)
|
||||||
|
far = sides[1] if local_side is sides[0] else sides[0]
|
||||||
|
if local_side is None or len(far) != 1 or _term(far[0], "object_type") != "dcim.interface":
|
||||||
|
report["cables_skipped"] += 1
|
||||||
|
return
|
||||||
|
if _term(far[0], "object_id") == remote.id:
|
||||||
|
report["cables_skipped"] += 1
|
||||||
|
return
|
||||||
|
old = _termination_text(far[0])
|
||||||
|
remote_cable = related_id(remote, "cable")
|
||||||
|
if not update_cables or (remote_cable and remote_cable != cable.id):
|
||||||
|
reason = ("Gegenstelle hat bereits ein anderes Kabel" if update_cables
|
||||||
|
else "„Bestehende Kabel anpassen“ ist aus")
|
||||||
|
report["notes"].append(f"Kabel {label}: in NetBox mit {old} verbunden – nicht angepasst ({reason})")
|
||||||
|
return
|
||||||
|
report["cables_updated"] += 1
|
||||||
|
report["changes"].append(f"⚠ Kabel {label}: ersetzt bisherige Gegenstelle {old}")
|
||||||
|
if not dry_run:
|
||||||
|
cable.update({
|
||||||
|
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
|
||||||
|
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
|
||||||
|
})
|
||||||
|
remote.cable = cable
|
||||||
|
|
||||||
|
|
||||||
|
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
|
||||||
|
backup_config=False, update_cables=False):
|
||||||
"""Write a discovery snapshot to NetBox.
|
"""Write a discovery snapshot to NetBox.
|
||||||
|
|
||||||
With ``dry_run`` nothing is written; the returned report lists what would
|
With ``dry_run`` nothing is written; the returned report lists what would
|
||||||
@@ -1600,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)
|
||||||
@@ -1611,7 +1847,8 @@ 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")
|
||||||
records = {}
|
_sync_switch_stack(nb, device, members, dry_run, report)
|
||||||
|
records, foreign = {}, set()
|
||||||
|
|
||||||
for interface in snapshot["interfaces"]:
|
for interface in snapshot["interfaces"]:
|
||||||
key = interface_key(interface["name"])
|
key = interface_key(interface["name"])
|
||||||
@@ -1621,7 +1858,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
record, method = matches[interface["name"]]
|
record, method = matches[interface["name"]]
|
||||||
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 = vlan_label(port["vlans"])
|
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 = {}
|
||||||
@@ -1631,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 = []
|
||||||
@@ -1656,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
|
||||||
@@ -1670,6 +1908,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
except Exception as error: # noqa: BLE001
|
except Exception as error: # noqa: BLE001
|
||||||
report["errors"].append(f"Interface {interface['name']}: {error}")
|
report["errors"].append(f"Interface {interface['name']}: {error}")
|
||||||
|
|
||||||
|
_sync_lag_members(snapshot, owners, records, dry_run, report)
|
||||||
|
|
||||||
for interface in snapshot["interfaces"]:
|
for interface in snapshot["interfaces"]:
|
||||||
key = interface_key(interface["name"])
|
key = interface_key(interface["name"])
|
||||||
if key not in records:
|
if key not in records:
|
||||||
@@ -1722,9 +1962,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
if key not in records:
|
if key not in records:
|
||||||
continue
|
continue
|
||||||
local = records[key]
|
local = records[key]
|
||||||
if local is not None and getattr(local, "cable", None):
|
existing = getattr(local, "cable", None) if local is not None else None
|
||||||
report["cables_skipped"] += 1
|
|
||||||
continue
|
|
||||||
if neighbor["local_port"] in manual_devices:
|
if neighbor["local_port"] in manual_devices:
|
||||||
# 0 means "no device" was chosen in the review dialog.
|
# 0 means "no device" was chosen in the review dialog.
|
||||||
chosen = int(manual_devices[neighbor["local_port"]] or 0)
|
chosen = int(manual_devices[neighbor["local_port"]] or 0)
|
||||||
@@ -1737,6 +1975,12 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
if remote_device.id in own_devices:
|
if remote_device.id in own_devices:
|
||||||
continue
|
continue
|
||||||
remote = lookup.interface(remote_device, neighbor)
|
remote = lookup.interface(remote_device, neighbor)
|
||||||
|
if existing:
|
||||||
|
if remote:
|
||||||
|
_check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report)
|
||||||
|
else:
|
||||||
|
report["cables_skipped"] += 1
|
||||||
|
continue
|
||||||
if not remote or getattr(remote, "cable", None):
|
if not remote or getattr(remote, "cable", None):
|
||||||
report["cables_skipped"] += 1
|
report["cables_skipped"] += 1
|
||||||
continue
|
continue
|
||||||
@@ -1752,6 +1996,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
|||||||
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
|
||||||
report["errors"].append(f"Nachbar {label}: {error}")
|
report["errors"].append(f"Nachbar {label}: {error}")
|
||||||
|
if backup_config:
|
||||||
|
_backup_config(nb, device, snapshot, dry_run, report)
|
||||||
return report
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -432,6 +432,8 @@ 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}
|
||||||
|
backup = self.state.settings.get("backup_config")
|
||||||
|
update_cables = create_cables and bool(self.state.settings.get("update_cables"))
|
||||||
# VLAN and network decisions are shared by all switches of the profile.
|
# VLAN and network decisions are shared by all switches of the profile.
|
||||||
vlan_map = self.state.profile.setdefault("vlan_map", {})
|
vlan_map = self.state.profile.setdefault("vlan_map", {})
|
||||||
network_map = self.state.profile.setdefault("network_map", {})
|
network_map = self.state.profile.setdefault("network_map", {})
|
||||||
@@ -498,7 +500,8 @@ class Actions:
|
|||||||
for index, (switch, snapshot) in enumerate(items):
|
for index, (switch, snapshot) in enumerate(items):
|
||||||
ctx.progress(index, len(items), switch["name"])
|
ctx.progress(index, len(items), switch["name"])
|
||||||
ctx.log(f"{switch['name']}: berechne Änderungen …")
|
ctx.log(f"{switch['name']}: berechne Änderungen …")
|
||||||
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True)))
|
reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True,
|
||||||
|
backup_config=backup, update_cables=update_cables)))
|
||||||
return nb, reports
|
return nb, reports
|
||||||
|
|
||||||
def show_preview(result):
|
def show_preview(result):
|
||||||
@@ -509,22 +512,26 @@ class Actions:
|
|||||||
# follow-up task is not rejected as "still busy".
|
# follow-up task is not rejected as "still busy".
|
||||||
dialog = SyncPreviewDialog(self.window, reports, create_cables)
|
dialog = SyncPreviewDialog(self.window, reports, create_cables)
|
||||||
if dialog.exec():
|
if dialog.exec():
|
||||||
self._apply_switch_sync(nb, items, create_cables, log)
|
self._apply_switch_sync(nb, items, create_cables, log, update_cables)
|
||||||
QTimer.singleShot(0, ask)
|
QTimer.singleShot(0, ask)
|
||||||
|
|
||||||
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
||||||
on_error=self._netbox_failed)
|
on_error=self._netbox_failed)
|
||||||
|
|
||||||
def _apply_switch_sync(self, nb, items, create_cables, log):
|
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False):
|
||||||
def work(ctx):
|
def work(ctx):
|
||||||
reports = []
|
reports = []
|
||||||
for index, (switch, snapshot) in enumerate(items):
|
for index, (switch, snapshot) in enumerate(items):
|
||||||
ctx.check_cancelled()
|
ctx.check_cancelled()
|
||||||
ctx.progress(index, len(items), switch["name"])
|
ctx.progress(index, len(items), switch["name"])
|
||||||
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
|
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
|
||||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False)
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False,
|
||||||
|
backup_config=self.state.settings.get("backup_config"),
|
||||||
|
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
|
||||||
|
|
||||||
|
|||||||
@@ -546,9 +546,14 @@ class SyncPreviewDialog(_Dialog):
|
|||||||
items.append((f"{totals[key]} {text}", "info"))
|
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"))
|
||||||
|
if totals.get("cables_updated"):
|
||||||
|
items.append((f"{totals['cables_updated']} Kabel angepasst", "error"))
|
||||||
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)
|
||||||
@@ -564,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)
|
||||||
@@ -593,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"))
|
||||||
@@ -976,12 +983,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)
|
||||||
|
|||||||
@@ -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, ignored_vlans, vlan_label, without_vlans
|
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, port_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
|
||||||
@@ -93,12 +93,23 @@ class SwitchesPage(Page):
|
|||||||
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
|
self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen",
|
||||||
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
|
tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox "
|
||||||
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
|
"eindeutig gefunden wird. Bestehende Kabel werden nie verändert.")
|
||||||
|
self.update_cables_option = checkbox(
|
||||||
|
"Bestehende Kabel anpassen",
|
||||||
|
tooltip="Achtung: NetBox ist die Source of Truth. Weicht ein vorhandenes Kabel vom LLDP/CDP-Nachbarn ab, "
|
||||||
|
"wird es auf die vom Switch gemeldete Gegenstelle umgehängt. Kabel zu Patchpanels werden nie "
|
||||||
|
"verändert. Ohne diese Option werden Abweichungen nur gemeldet.")
|
||||||
|
self.backup_option = checkbox("Konfiguration als Anhang sichern",
|
||||||
|
tooltip="Hängt die laufende Konfiguration als Textdatei an das NetBox-Gerät "
|
||||||
|
"(Plugin netbox-attachments). Passwörter, Schlüssel und Communities "
|
||||||
|
"werden entfernt; ein neuer Anhang entsteht nur bei Änderungen.")
|
||||||
filters.addWidget(self.search, 2)
|
filters.addWidget(self.search, 2)
|
||||||
filters.addWidget(self.switch_filter, 1)
|
filters.addWidget(self.switch_filter, 1)
|
||||||
filters.addWidget(self.only_up)
|
filters.addWidget(self.only_up)
|
||||||
filters.addWidget(self.only_neighbors)
|
filters.addWidget(self.only_neighbors)
|
||||||
filters.addStretch(1)
|
filters.addStretch(1)
|
||||||
filters.addWidget(self.cables_option)
|
filters.addWidget(self.cables_option)
|
||||||
|
filters.addWidget(self.update_cables_option)
|
||||||
|
filters.addWidget(self.backup_option)
|
||||||
result_card.add(filters)
|
result_card.add(filters)
|
||||||
result_columns = [
|
result_columns = [
|
||||||
Column("switch", "Switch", 140),
|
Column("switch", "Switch", 140),
|
||||||
@@ -108,8 +119,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(without_vlans(
|
Column("vlans", "VLANs", 110, value=lambda row: port_label(without_vlans(
|
||||||
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
|
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))), row.get("lag"))),
|
||||||
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", "")),
|
||||||
@@ -144,6 +155,9 @@ class SwitchesPage(Page):
|
|||||||
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
|
self.switch_table.selectionModel().selectionChanged.connect(self._update_buttons)
|
||||||
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
|
self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
|
||||||
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
|
self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value))
|
||||||
|
self.backup_option.toggled.connect(lambda value: self.state.update_settings(backup_config=value))
|
||||||
|
self.update_cables_option.toggled.connect(self._toggle_update_cables)
|
||||||
|
self.cables_option.toggled.connect(self.update_cables_option.setEnabled)
|
||||||
self.state.switches_changed.connect(self.refresh)
|
self.state.switches_changed.connect(self.refresh)
|
||||||
self.state.profile_switched.connect(self.refresh)
|
self.state.profile_switched.connect(self.refresh)
|
||||||
self.state.profile_edited.connect(self.refresh_switches)
|
self.state.profile_edited.connect(self.refresh_switches)
|
||||||
@@ -155,10 +169,25 @@ class SwitchesPage(Page):
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def _load_settings(self):
|
def _load_settings(self):
|
||||||
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables")):
|
for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables"),
|
||||||
|
(self.backup_option, "backup_config"), (self.update_cables_option, "update_cables")):
|
||||||
widget.blockSignals(True)
|
widget.blockSignals(True)
|
||||||
widget.setChecked(bool(self.state.settings.get(key)))
|
widget.setChecked(bool(self.state.settings.get(key)))
|
||||||
widget.blockSignals(False)
|
widget.blockSignals(False)
|
||||||
|
self.update_cables_option.setEnabled(self.cables_option.isChecked())
|
||||||
|
|
||||||
|
def _toggle_update_cables(self, value):
|
||||||
|
if value and not widgets.confirm(
|
||||||
|
self.window, "Bestehende Kabel anpassen?",
|
||||||
|
"NetBox ist die Source of Truth. Mit dieser Option werden vorhandene Kabel, deren Gegenstelle nicht "
|
||||||
|
"zum LLDP/CDP-Nachbarn des Switches passt, umgehängt – die bisherige Verbindung geht in NetBox "
|
||||||
|
"verloren. Kabel zu Patchpanels bleiben unverändert. Jede Anpassung steht vorher in der Vorschau.",
|
||||||
|
ok_text="Einschalten", destructive=True):
|
||||||
|
self.update_cables_option.blockSignals(True)
|
||||||
|
self.update_cables_option.setChecked(False)
|
||||||
|
self.update_cables_option.blockSignals(False)
|
||||||
|
return
|
||||||
|
self.state.update_settings(update_cables=value)
|
||||||
|
|
||||||
def _status_text(self, row):
|
def _status_text(self, row):
|
||||||
status = self.state.switch_status.get(row["id"])
|
status = self.state.switch_status.get(row["id"])
|
||||||
|
|||||||
@@ -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
|
||||||
+238
-1
@@ -1,12 +1,15 @@
|
|||||||
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,
|
||||||
|
mask_config,
|
||||||
match_interfaces,
|
match_interfaces,
|
||||||
|
parse_lags,
|
||||||
parse_stack,
|
parse_stack,
|
||||||
plan_switch_sync,
|
plan_switch_sync,
|
||||||
|
port_label,
|
||||||
stack_member,
|
stack_member,
|
||||||
sync_snapshot_to_netbox,
|
sync_snapshot_to_netbox,
|
||||||
)
|
)
|
||||||
@@ -366,6 +369,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()
|
||||||
@@ -375,3 +404,211 @@ def test_virtual_chassis_positions_are_suggested():
|
|||||||
virtual_chassis=SimpleNamespace(id=9), vc_position=2))
|
virtual_chassis=SimpleNamespace(id=9), vc_position=2))
|
||||||
plan = plan_switch_sync(nb, switch, snapshot)
|
plan = plan_switch_sync(nb, switch, snapshot)
|
||||||
assert [entry["device_id"] for entry in plan["stack"]] == [1, 4]
|
assert [entry["device_id"] for entry in plan["stack"]] == [1, 4]
|
||||||
|
|
||||||
|
|
||||||
|
CX_LAG_BRIEF = """
|
||||||
|
Port Native Mode Type Enabled Status Reason Speed Description
|
||||||
|
1/1/1 1 trunk 10G-SR yes up 10000 SOEM-E1
|
||||||
|
1/1/2 1 trunk 10G-SR yes up 10000 SOEM-E1
|
||||||
|
1/1/23 120 access 1G-BT yes up 1000 FritzBox
|
||||||
|
lag1 1 trunk -- yes up -- 20000 Etage 1 Uplink
|
||||||
|
"""
|
||||||
|
|
||||||
|
CX_LAG_CONFIG = """vlan 1
|
||||||
|
vlan 100
|
||||||
|
interface lag 1
|
||||||
|
no routing
|
||||||
|
vlan trunk native 1
|
||||||
|
vlan trunk allowed 100,110,120,201,209-213
|
||||||
|
interface 1/1/1
|
||||||
|
no shutdown
|
||||||
|
lag 1
|
||||||
|
interface 1/1/2
|
||||||
|
no shutdown
|
||||||
|
lag 1
|
||||||
|
interface 1/1/23
|
||||||
|
no routing
|
||||||
|
vlan access 120
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def test_lags_are_parsed_for_all_platforms():
|
||||||
|
assert parse_lags(CX_LAG_CONFIG, "aruba_cx") == {"1/1/1": "lag1", "1/1/2": "lag1"}
|
||||||
|
assert parse_lags("trunk 49-50 trk1 lacp\ntrunk 1/A1-1/A2 Trk2 trunk\n", "aruba_aos") == {
|
||||||
|
"49": "Trk1", "50": "Trk1", "1/a1": "Trk2", "1/a2": "Trk2"}
|
||||||
|
comware = "interface GigabitEthernet1/0/49\n port link-aggregation group 3\n#\n"
|
||||||
|
assert parse_lags(comware, "hpe_comware") == {"ge1/0/49": "Bridge-Aggregation3"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_lag_members_take_the_lag_vlans_and_name_the_lag_in_the_label():
|
||||||
|
snapshot = build_snapshot({"interfaces": CX_LAG_BRIEF, "neighbors": "", "config": CX_LAG_CONFIG}, "aruba_cx")
|
||||||
|
ports = {item["name"]: item for item in snapshot["interfaces"]}
|
||||||
|
assert ports["1/1/1"]["lag"] == "lag1" and ports["1/1/23"]["lag"] is None
|
||||||
|
assert port_label(ports["1/1/1"]["vlans"], ports["1/1/1"]["lag"]) == "1,100,110,120,201,209-213 (LAG 1)"
|
||||||
|
assert port_label(ports["1/1/23"]["vlans"], ports["1/1/23"]["lag"]) == "120"
|
||||||
|
assert port_label(None, "Trk2") == "(LAG 2)"
|
||||||
|
assert len(port_label({"untagged": [], "tagged": list(range(2, 400, 2)), "tagged_all": False}, "lag1")) <= 64
|
||||||
|
assert " lag 1" in snapshot["raw"]["vlan_config"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_lag_members_are_assigned_to_their_lag_in_netbox():
|
||||||
|
nb, switch, snapshot = _numbered_setup()
|
||||||
|
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=30, name="lag1", device=SimpleNamespace(id=1),
|
||||||
|
type=SimpleNamespace(value="lag"), enabled=True, cable=None, label=""))
|
||||||
|
snapshot["interfaces"].append({"name": "lag1", "enabled": True, "connected": True, "ip_addresses": [],
|
||||||
|
"vlans": None})
|
||||||
|
for item in snapshot["interfaces"][:2]:
|
||||||
|
item["lag"] = "lag1"
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||||
|
assert "Interface 1: LAG lag1" in report["changes"] and nb.dcim.interfaces.updates == []
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||||
|
assert nb.dcim.interfaces.get(1).lag == 30 and nb.dcim.interfaces.get(1).label == "10 (LAG 1)"
|
||||||
|
assert not getattr(nb.dcim.interfaces.get(3), "lag", None)
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||||
|
assert not any("LAG lag1" in change for change in report["changes"]), "already assigned"
|
||||||
|
|
||||||
|
|
||||||
|
class _AttachmentEndpoint(Endpoint):
|
||||||
|
def create(self, payload):
|
||||||
|
record = super().create(payload)
|
||||||
|
if self.assignments is not None:
|
||||||
|
record.assignments = []
|
||||||
|
return record
|
||||||
|
|
||||||
|
def filter(self, **kwargs):
|
||||||
|
query = kwargs.pop("q", "")
|
||||||
|
return [item for item in super().filter(**kwargs) if query in (getattr(item, "description", "") or "")]
|
||||||
|
|
||||||
|
|
||||||
|
def _attachments(newer=True):
|
||||||
|
attachments = _AttachmentEndpoint()
|
||||||
|
attachments.assignments = [] if newer else None
|
||||||
|
return SimpleNamespace(netbox_attachments=attachments, netbox_attachment_assignments=Endpoint())
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_backup_masks_secrets():
|
||||||
|
config = ('hostname core\nuser admin group administrators password ciphertext AQBapW==\n'
|
||||||
|
'snmp-server community geheim\nradius-server host 10.0.0.1 key plaintext topsecret\n')
|
||||||
|
masked = mask_config(config)
|
||||||
|
assert "AQBapW" not in masked and "geheim" not in masked and "topsecret" not in masked
|
||||||
|
assert "hostname core" in masked and "password <entfernt>" in masked
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_is_attached_only_when_it_changed():
|
||||||
|
nb, switch, snapshot = _numbered_setup()
|
||||||
|
snapshot["config_backup"] = "hostname access-01"
|
||||||
|
# Without the plugin nothing happens.
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||||
|
assert not report["errors"]
|
||||||
|
|
||||||
|
nb.plugins = SimpleNamespace(netbox_attachments=_attachments())
|
||||||
|
app = nb.plugins.netbox_attachments
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
|
||||||
|
assert any(change.startswith("Konfigurations-Backup: Anhang „Running-Config access-01")
|
||||||
|
for change in report["changes"]) and app.netbox_attachments.created == []
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||||
|
payload = app.netbox_attachments.created[0]
|
||||||
|
assert payload["file"][1].getvalue() == b"hostname access-01" and payload["file"][0].endswith(".txt")
|
||||||
|
assert app.netbox_attachment_assignments.created == [
|
||||||
|
{"attachment": app.netbox_attachments.records[0].id, "object_type": "dcim.device", "object_id": 1}]
|
||||||
|
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True, backup_config=True)
|
||||||
|
assert not any("Konfigurations-Backup" in change for change in report["changes"]), "unchanged"
|
||||||
|
snapshot["config_backup"] = "hostname access-01\nvlan 10"
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||||
|
assert len(app.netbox_attachments.created) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_backup_with_older_attachment_plugin():
|
||||||
|
nb, switch, snapshot = _numbered_setup()
|
||||||
|
snapshot["config_backup"] = "hostname access-01"
|
||||||
|
nb.plugins = SimpleNamespace(netbox_attachments=_attachments(newer=False))
|
||||||
|
app = nb.plugins.netbox_attachments
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, backup_config=True)
|
||||||
|
payload = app.netbox_attachments.created[0]
|
||||||
|
assert (payload["object_type"], payload["object_id"]) == ("dcim.device", 1)
|
||||||
|
assert app.netbox_attachment_assignments.created == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_cable_to_access_point_that_reports_its_mac_as_port():
|
||||||
|
nb, switch, snapshot = _numbered_setup()
|
||||||
|
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
|
||||||
|
nb.dcim.interfaces.records += [
|
||||||
|
Record(nb.dcim.interfaces, id=50, name="LAN", device=SimpleNamespace(id=5), mac_address="C8:4F:86:88:96:8E",
|
||||||
|
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||||
|
Record(nb.dcim.interfaces, id=51, name="LAN2", device=SimpleNamespace(id=5), mac_address=None,
|
||||||
|
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None),
|
||||||
|
]
|
||||||
|
snapshot["neighbors"][0].update(system_name="AP6420-PA3007MFJ3BDX1A", remote_port="c8:4f:86:88:96:8e")
|
||||||
|
switch["neighbor_devices"] = {"1/1/2": 5}
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||||
|
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
|
||||||
|
|
||||||
|
# A device with a single port is cabled there even if neither name nor MAC match.
|
||||||
|
nb, switch, snapshot = _numbered_setup()
|
||||||
|
nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7)))
|
||||||
|
nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=50, name="eth0", device=SimpleNamespace(id=5),
|
||||||
|
type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None))
|
||||||
|
snapshot["neighbors"][0].update(system_name="AP6420", remote_port="c8:4f:86:88:96:cc")
|
||||||
|
switch["neighbor_devices"] = {"1/1/2": 5}
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||||
|
assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}]
|
||||||
|
|
||||||
|
|
||||||
|
def _cabled_setup(far_type="dcim.interface"):
|
||||||
|
"""Port 1/1/2 (NetBox "2") has a cable to "old-device eth9"; LLDP reports server-01 eth0."""
|
||||||
|
nb, switch, snapshot = _numbered_setup()
|
||||||
|
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
|
||||||
|
far = {"object_type": far_type, "object_id": 99,
|
||||||
|
"object": {"name": "eth9", "device": {"name": "old-device"}}}
|
||||||
|
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70, a_terminations=[far],
|
||||||
|
b_terminations=[{"object_type": "dcim.interface", "object_id": 2}]))
|
||||||
|
switch["neighbor_devices"] = {"1/1/2": 2}
|
||||||
|
return nb, switch, snapshot
|
||||||
|
|
||||||
|
|
||||||
|
def test_differing_cable_is_only_reported_by_default():
|
||||||
|
nb, switch, snapshot = _cabled_setup()
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot)
|
||||||
|
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == []
|
||||||
|
assert any("in NetBox mit old-device eth9 verbunden – nicht angepasst" in note for note in report["notes"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_differing_cable_is_moved_when_allowed():
|
||||||
|
nb, switch, snapshot = _cabled_setup()
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True, update_cables=True)
|
||||||
|
assert report["cables_updated"] == 1 and nb.dcim.cables.updates == []
|
||||||
|
assert any(change.startswith("⚠ Kabel access-01") and "old-device eth9" in change for change in report["changes"])
|
||||||
|
sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||||
|
assert nb.dcim.cables.updates == [(70, {
|
||||||
|
"a_terminations": [{"object_type": "dcim.interface", "object_id": 2}],
|
||||||
|
"b_terminations": [{"object_type": "dcim.interface", "object_id": 20}]})]
|
||||||
|
assert nb.dcim.cables.created == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_cables_to_patch_panels_and_busy_far_ends_are_kept():
|
||||||
|
nb, switch, snapshot = _cabled_setup(far_type="dcim.frontport")
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||||
|
assert report["cables_updated"] == 0 and nb.dcim.cables.updates == [] and not report["notes"]
|
||||||
|
|
||||||
|
nb, switch, snapshot = _cabled_setup()
|
||||||
|
nb.dcim.interfaces.get(20).cable = SimpleNamespace(id=71)
|
||||||
|
report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True)
|
||||||
|
assert nb.dcim.cables.updates == []
|
||||||
|
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