Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52680e5b7c | ||
|
|
1968098b63 | ||
|
|
17c010ecbc | ||
|
|
dbaf2a83c0 | ||
|
|
bdada6fe14 | ||
|
|
698086a6aa |
No files matched your search
@@ -86,7 +86,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
decisions are stored per profile (shared by all its switches); only VLANs
|
||||
that still need a decision are shown, stored and unambiguous ones are in a
|
||||
collapsed section that can be expanded for editing. Mapped VLANs are assigned
|
||||
to the ports (802.1Q mode, untagged/tagged)
|
||||
to the ports (802.1Q mode, untagged/tagged). The interface at the other end
|
||||
of a port's cable (e.g. a router or access point) is kept in step: VLANs it
|
||||
is missing are added, VLANs the switch port no longer carries are removed;
|
||||
other VLANs there stay. After the preview the app asks before changing these
|
||||
far ends ("Nur Switch" syncs the switch alone)
|
||||
- Tenant required: a switch without tenant in NetBox is refused; every created
|
||||
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
|
||||
- Stacks are detected (Aruba CX VSF, ArubaOS-Switch stacking/VSF, HPE Comware
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
#define AppName "NetBox Synchronizer"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "4.21.0"
|
||||
#define AppVersion "4.22.0"
|
||||
#endif
|
||||
#define AppPublisher "Louis-Alexander Kerst"
|
||||
#define AppExeName "NetBoxSynchronizer.exe"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
|
||||
|
||||
APP_NAME = "NetBox Synchronizer"
|
||||
APP_VERSION = "4.21.0"
|
||||
APP_VERSION = "4.22.0"
|
||||
APP_PUBLISHER = "Louis-Alexander Kerst"
|
||||
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
|
||||
|
||||
|
||||
@@ -378,12 +378,17 @@ class PrinterSyncEngine(APSyncEngine):
|
||||
key=lambda row: (row["manufacturer"].casefold(), row["model"].casefold()))
|
||||
return result
|
||||
|
||||
def existing_type(self, printer):
|
||||
"""NetBox device type row of ``printer`` (same manufacturer and model), or ``None``."""
|
||||
manufacturer, model, _platform = self._identity(printer)
|
||||
return next((row for row in self.device_types if row["model"].casefold() == model.casefold()
|
||||
and row["manufacturer"].casefold() in (
|
||||
manufacturer.casefold(), "hewlett-packard" if manufacturer.casefold() == "hp" else "")),
|
||||
None)
|
||||
|
||||
def type_exists(self, printer):
|
||||
"""Is the device type of ``printer`` already in NetBox (same manufacturer and model)?"""
|
||||
manufacturer, model, _platform = self._identity(printer)
|
||||
return any(row["model"].casefold() == model.casefold() and row["manufacturer"].casefold() in (
|
||||
manufacturer.casefold(), "hewlett-packard" if manufacturer.casefold() == "hp" else "")
|
||||
for row in self.device_types)
|
||||
return self.existing_type(printer) is not None
|
||||
|
||||
def suggest_type(self, printer):
|
||||
"""Device type with a similar model name, or ``None``."""
|
||||
@@ -398,6 +403,20 @@ class PrinterSyncEngine(APSyncEngine):
|
||||
def _mapped_type(self, printer):
|
||||
return self.type_map.get(model_key(printer))
|
||||
|
||||
# Printer device types are never created: only existing or manually chosen ones are used.
|
||||
|
||||
def _manufacturer(self, name, report, dry_run):
|
||||
return None
|
||||
|
||||
def _device_type(self, manufacturer_name, manufacturer_id, model, report, dry_run):
|
||||
hp = "hewlett-packard" if manufacturer_name.casefold() == "hp" else ""
|
||||
found = next((row["id"] for row in self.device_types if row["model"].casefold() == model.casefold()
|
||||
and row["manufacturer"].casefold() in (manufacturer_name.casefold(), hp)), None)
|
||||
if found is None:
|
||||
raise PrinterError(f"Gerätetyp „{manufacturer_name} {model}“ fehlt in NetBox – bitte unter "
|
||||
"„Modelle …“ einen vorhandenen Gerätetyp wählen")
|
||||
return found
|
||||
|
||||
def _known_devices(self, scope):
|
||||
if not self.role_id:
|
||||
return []
|
||||
|
||||
@@ -1920,7 +1920,7 @@ def _check_cable(nb, local, remote, label, update_cables, dry_run, report):
|
||||
|
||||
|
||||
def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop,
|
||||
backup_config=False, update_cables=False):
|
||||
backup_config=False, update_cables=False, sync_peer_vlans=True):
|
||||
"""Write a discovery snapshot to NetBox.
|
||||
|
||||
With ``dry_run`` nothing is written; the returned report lists what would
|
||||
@@ -1950,7 +1950,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
and stack_member(name, snapshot.get("platform")) == member)
|
||||
report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen")
|
||||
_sync_switch_stack(nb, device, members, dry_run, report)
|
||||
records, foreign = {}, set()
|
||||
records, foreign, port_vlans, old_vlans = {}, set(), {}, {}
|
||||
|
||||
for interface in snapshot["interfaces"]:
|
||||
key = interface_key(interface["name"])
|
||||
@@ -1962,6 +1962,13 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
|
||||
label = port_label(port["vlans"], interface.get("lag"))
|
||||
owner_vlans = _vlans_for_site(vlan_ids, vlan_sites, related_id(owner, "site"), owner, foreign, report)
|
||||
if netbox_interface_type(interface) != "virtual":
|
||||
port_vlans[key] = port["vlans"] or {}
|
||||
if record:
|
||||
# VLANs the port had before this run – the ones it loses are removed at the far end, too.
|
||||
old_vlans[key] = ({related_id(record, "untagged_vlan")}
|
||||
| {getattr(item, "id", item) for item in getattr(record, "tagged_vlans", None) or []})
|
||||
old_vlans[key].discard(None)
|
||||
try:
|
||||
if record:
|
||||
changes = {}
|
||||
@@ -2054,6 +2061,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"IP-Adresse {address} auf {interface['name']}: {error}")
|
||||
|
||||
new_peers = {}
|
||||
if create_cables:
|
||||
lookup = _RemoteLookup(nb)
|
||||
manual_devices = config.get("neighbor_devices") or {}
|
||||
@@ -2120,13 +2128,92 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
"tenant": tenant_id,
|
||||
})
|
||||
remote.cable = True # avoid a second cable from the reverse direction
|
||||
new_peers[key] = remote
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Nachbar {label}: {error}")
|
||||
if sync_peer_vlans:
|
||||
_sync_peer_vlans(nb, records, port_vlans, old_vlans, new_peers, vlan_ids, vlan_sites, own_devices, dry_run, report)
|
||||
if backup_config:
|
||||
_backup_config(nb, device, snapshot, dry_run, report)
|
||||
return report
|
||||
|
||||
|
||||
def _cable_peer(nb, record):
|
||||
"""The single far-end interface of ``record``'s cable, or ``None``."""
|
||||
cable_id = related_id(record, "cable")
|
||||
if not cable_id:
|
||||
return None
|
||||
cable = nb.dcim.cables.get(cable_id)
|
||||
if cable is None:
|
||||
return None
|
||||
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") == record.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":
|
||||
return None
|
||||
return nb.dcim.interfaces.get(_term(far[0], "object_id"))
|
||||
|
||||
|
||||
def _sync_peer_vlans(nb, records, port_vlans, old_vlans, new_peers, vlan_ids, vlan_sites, own_devices, dry_run, report):
|
||||
"""Keep the interface at the other end of each switch port's cable in step with the port.
|
||||
|
||||
VLANs the port carries are added; VLANs the port carried before this run but
|
||||
no longer does are removed. Other VLANs of the far end stay untouched. Devices
|
||||
synced by this run are skipped, so the far end never has to be maintained by hand.
|
||||
"""
|
||||
site_cache = {}
|
||||
for key, vlans in port_vlans.items():
|
||||
record = records.get(key)
|
||||
try:
|
||||
peer = new_peers.get(key)
|
||||
if peer is not None and not isinstance(getattr(peer, "id", None), int):
|
||||
peer = None
|
||||
if peer is None and record is not None and not isinstance(getattr(record, "cable", None), bool):
|
||||
peer = _cable_peer(nb, record)
|
||||
if peer is None:
|
||||
continue
|
||||
peer_device = related_id(peer, "device")
|
||||
if peer_device in own_devices or vlans.get("tagged_all"):
|
||||
continue
|
||||
port_ids = {vlan_ids[vid] for vid in list(vlans.get("untagged", [])) + list(vlans.get("tagged", []))
|
||||
if vid in vlan_ids}
|
||||
removed = old_vlans.get(key, set()) - port_ids
|
||||
if peer_device not in site_cache:
|
||||
site_cache[peer_device] = related_id(nb.dcim.devices.get(peer_device), "site")
|
||||
peer_site = site_cache[peer_device]
|
||||
|
||||
def allowed(vid):
|
||||
return vid in vlan_ids and vlan_sites.get(vid, (None,))[0] in (None, peer_site)
|
||||
|
||||
mode = _record_mode(peer)
|
||||
if mode == "tagged-all":
|
||||
continue
|
||||
current_untagged = related_id(peer, "untagged_vlan")
|
||||
current_tagged = {getattr(item, "id", item) for item in getattr(peer, "tagged_vlans", None) or []}
|
||||
untagged = next((vlan_ids[vid] for vid in vlans.get("untagged", []) if allowed(vid)), None)
|
||||
tagged = {vlan_ids[vid] for vid in vlans.get("tagged", []) if allowed(vid)}
|
||||
kept_untagged = None if current_untagged in removed else current_untagged
|
||||
new_untagged = kept_untagged or untagged
|
||||
new_tagged = ((current_tagged - removed) | tagged) - {new_untagged}
|
||||
if new_untagged == current_untagged and new_tagged == current_tagged:
|
||||
continue
|
||||
new_mode = "tagged" if new_tagged else "access" if new_untagged else None
|
||||
peer_name = f"{_term(_term(peer, 'device') or {}, 'name') or peer_device} {peer.name}"
|
||||
before = current_tagged | ({current_untagged} - {None})
|
||||
after = new_tagged | ({new_untagged} - {None})
|
||||
texts = []
|
||||
if after - before:
|
||||
texts.append(f"{len(after - before)} VLAN(s) vom Switch-Port übernommen")
|
||||
if before - after:
|
||||
texts.append(f"{len(before - after)} VLAN(s) entfernt (am Switch-Port weggefallen)")
|
||||
report["changes"].append(f"Gegenstelle {peer_name}: {', '.join(texts) or 'VLAN-Zuordnung angepasst'}")
|
||||
if not dry_run:
|
||||
peer.update({"mode": new_mode, "untagged_vlan": new_untagged,
|
||||
"tagged_vlans": sorted(new_tagged, key=str)})
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"VLANs der Gegenstelle von {key}: {error}")
|
||||
|
||||
|
||||
def describe_snapshot(snapshot):
|
||||
stack = snapshot.get("stack") or []
|
||||
return (
|
||||
|
||||
@@ -567,14 +567,23 @@ class Actions:
|
||||
# Opened after the preview task has fully finished, so the
|
||||
# follow-up task is not rejected as "still busy".
|
||||
dialog = SyncPreviewDialog(self.window, reports, create_cables)
|
||||
if dialog.exec():
|
||||
self._apply_switch_sync(nb, items, create_cables, log, update_cables)
|
||||
if not dialog.exec():
|
||||
return
|
||||
peers = [f"{switch['name']}: {change}" for switch, report in reports
|
||||
for change in report["changes"] if change.startswith("Gegenstelle ")]
|
||||
sync_peers = not peers or widgets.confirm(
|
||||
self.window, "Gegenstellen anpassen?",
|
||||
f"An {len(peers)} per Kabel verbundenen Schnittstelle(n) anderer Geräte weichen die VLANs vom "
|
||||
"Switch-Port ab. Sollen sie angeglichen werden (fehlende ergänzen, am Switch weggefallene "
|
||||
"entfernen)? Ohne Anpassung wird nur der Switch synchronisiert.",
|
||||
ok_text="Angleichen", cancel_text="Nur Switch", details="\n".join(peers))
|
||||
self._apply_switch_sync(nb, items, create_cables, log, update_cables, sync_peers)
|
||||
QTimer.singleShot(0, ask)
|
||||
|
||||
self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review,
|
||||
on_error=self._netbox_failed)
|
||||
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False):
|
||||
def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False, sync_peers=True):
|
||||
def work(ctx):
|
||||
reports = []
|
||||
for index, (switch, snapshot) in enumerate(items):
|
||||
@@ -583,7 +592,7 @@ class Actions:
|
||||
ctx.log(f"{switch['name']}: übertrage nach NetBox …")
|
||||
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)
|
||||
update_cables=update_cables, sync_peer_vlans=sync_peers)
|
||||
for error in report["errors"]:
|
||||
ctx.log(f"{switch['name']}: {error}", "error")
|
||||
for note in report.get("notes", []):
|
||||
|
||||
@@ -48,11 +48,12 @@ class SiteMappingDialog(_Dialog):
|
||||
"""Assign an optional NetBox site and the mandatory tenant to Sophos sites
|
||||
and to APs without a Sophos site."""
|
||||
|
||||
def __init__(self, parent, rows, sites, tenants, header="Sophos-Standort / Access Point", noun="APs"):
|
||||
def __init__(self, parent, rows, sites, tenants, header="Sophos-Standort / Access Point", noun="APs",
|
||||
empty_rows="Zeilen ohne Standort und ohne Mandant werden ignoriert."):
|
||||
super().__init__(parent, "Standorte & Mandanten zuordnen",
|
||||
f"Der Standort ist optional – {noun} ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
|
||||
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht und wird bewusst gewählt. Zeilen ohne "
|
||||
"Standort und ohne Mandant werden ignoriert.",
|
||||
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht und wird bewusst gewählt. "
|
||||
+ empty_rows,
|
||||
width=860)
|
||||
self.resize(980, 620)
|
||||
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
|
||||
@@ -109,6 +110,7 @@ class AccessPointsPage(Page):
|
||||
key_func = staticmethod(ap_key)
|
||||
mapping_header = "Sophos-Standort / Access Point"
|
||||
mapping_noun = "APs"
|
||||
mapping_options = {}
|
||||
subtitle = ("Sophos-APs aus einem Export von Sophos Central laden, mit NetBox abgleichen (global über "
|
||||
"Seriennummer, MAC und Name) und fehlende anlegen.")
|
||||
|
||||
@@ -257,14 +259,23 @@ class AccessPointsPage(Page):
|
||||
|
||||
def work(ctx):
|
||||
nb = connect(ctx)
|
||||
ctx.log("Lade Geräterollen …")
|
||||
return sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
|
||||
ctx.log("Lade Geräterollen und Standorte …")
|
||||
roles = sorted(((item.name, item.id) for item in nb.dcim.device_roles.all()), key=lambda x: x[0].casefold())
|
||||
tenants = {item.id: item.name for item in nb.tenancy.tenants.all()}
|
||||
sites = sorted(((site.name + (f" ({tenants[related_id(site, 'tenant')]})"
|
||||
if related_id(site, "tenant") in tenants else ""), site.id)
|
||||
for site in nb.dcim.sites.all()), key=lambda x: x[0].casefold())
|
||||
return roles, sites
|
||||
|
||||
def done(roles):
|
||||
def done(result):
|
||||
roles, sites = result
|
||||
self.roles = roles
|
||||
settings = self._settings()
|
||||
role_id = settings.get("role_id") or self._suggest_role(roles)
|
||||
self.role.set_items(roles, role_id)
|
||||
# the default site can be chosen before the first comparison
|
||||
if not self.engine:
|
||||
self.default_site.set_items(sites, settings.get("default_site"))
|
||||
if then_compare:
|
||||
QTimer.singleShot(0, self.compare)
|
||||
|
||||
@@ -434,7 +445,7 @@ class AccessPointsPage(Page):
|
||||
self.window.toast(f"Alle {self.noun} sind bereits in NetBox.", "info")
|
||||
return False
|
||||
dialog = SiteMappingDialog(self.window, rows, self.engine.ap_sites, self.engine.group_tenants,
|
||||
self.mapping_header, self.mapping_noun)
|
||||
self.mapping_header, self.mapping_noun, **self.mapping_options)
|
||||
if not dialog.exec():
|
||||
return False
|
||||
settings = self._settings()
|
||||
|
||||
@@ -12,6 +12,7 @@ from PySide6.QtWidgets import (
|
||||
QStackedWidget,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QToolButton,
|
||||
)
|
||||
|
||||
from netbox_sync.core import netscan, printers, snmp
|
||||
@@ -34,7 +35,7 @@ from netbox_sync.ui.widgets import (
|
||||
label,
|
||||
)
|
||||
|
||||
MODEL_ACTIONS = (("create", "Gerätetyp neu anlegen"), ("map", "Vorhandenen Gerätetyp verwenden"),
|
||||
MODEL_ACTIONS = (("map", "Vorhandenen Gerätetyp verwenden"),
|
||||
("skip", "Diesmal überspringen"), ("ignore", "Dauerhaft ignorieren"))
|
||||
AUTH_CHOICES = ["", *snmp.AUTH_PROTOCOLS]
|
||||
PRIV_CHOICES = ["", *snmp.PRIV_PROTOCOLS]
|
||||
@@ -194,10 +195,12 @@ class SnmpCredentialsDialog(_Dialog):
|
||||
class ModelMappingDialog(_Dialog):
|
||||
"""Decide per printer model that is missing in NetBox: create, map to an existing type, skip or ignore."""
|
||||
|
||||
def __init__(self, parent, rows, device_types):
|
||||
def __init__(self, parent, rows, device_types, others=()):
|
||||
super().__init__(parent, "Modelle zuordnen",
|
||||
"Diese Modelle gibt es in NetBox noch nicht als Gerätetyp. Pro Modell: neu anlegen, einen "
|
||||
"vorhandenen Gerätetyp verwenden, die Drucker dieses Modells diesmal überspringen oder dauerhaft "
|
||||
"Hier stehen nur Modelle, die es in NetBox nicht als Gerätetyp gibt"
|
||||
+ (f" – die übrigen {len(others)} neuen Drucker haben einen und werden normal übertragen"
|
||||
if others else "") + ". Gerätetypen werden nicht automatisch angelegt – pro Modell einen "
|
||||
"vorhandenen Gerätetyp wählen, die Drucker dieses Modells diesmal überspringen oder dauerhaft "
|
||||
"ignorieren (gespeichert im Profil).", width=900)
|
||||
self.resize(1040, 520)
|
||||
type_items = [(f"{row['manufacturer']} {row['model']}".strip(), row["id"]) for row in device_types]
|
||||
@@ -214,7 +217,7 @@ class ModelMappingDialog(_Dialog):
|
||||
action.addItem(caption, value)
|
||||
device_type = SearchableComboBox("Gerätetyp suchen …")
|
||||
device_type.set_items(type_items, decision.get("device_type") or suggestion)
|
||||
chosen = decision.get("action") or ("map" if suggestion else "create")
|
||||
chosen = decision.get("action") if decision.get("action") in dict(MODEL_ACTIONS) else "map"
|
||||
action.setCurrentIndex(next(index for index, (value, _c) in enumerate(MODEL_ACTIONS) if value == chosen))
|
||||
action.currentIndexChanged.connect(lambda _i, a=action, d=device_type: d.setEnabled(a.currentData() == "map"))
|
||||
device_type.setEnabled(chosen == "map")
|
||||
@@ -229,11 +232,42 @@ class ModelMappingDialog(_Dialog):
|
||||
for column, width in enumerate((330, 60, 250, 300)):
|
||||
self.table.setColumnWidth(column, width)
|
||||
self.root.addWidget(self.table, 1)
|
||||
if others:
|
||||
self._add_others(others)
|
||||
self.root.addWidget(self.error_banner)
|
||||
buttons, _ok = form_dialog_buttons(self, "Übernehmen")
|
||||
self.root.addWidget(buttons)
|
||||
self.result = {}
|
||||
|
||||
def _add_others(self, others):
|
||||
"""Collapsed list of the new printers whose device type exists – they need no decision here."""
|
||||
caption = f"Weitere neue Drucker mit vorhandenem Gerätetyp ({len(others)})"
|
||||
toggle = QToolButton()
|
||||
toggle.setText(caption)
|
||||
toggle.setCheckable(True)
|
||||
toggle.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
|
||||
toggle.setArrowType(Qt.RightArrow)
|
||||
toggle.setAutoRaise(True)
|
||||
table = QTableWidget(len(others), 3)
|
||||
table.setHorizontalHeaderLabels(["Drucker", "Hersteller / Modell (SNMP)", "Gerätetyp in NetBox"])
|
||||
for row, (name, model, device_type) in enumerate(others):
|
||||
for column, text in enumerate((name, model, device_type)):
|
||||
table.setItem(row, column, QTableWidgetItem(text))
|
||||
table.verticalHeader().hide()
|
||||
table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
table.setSelectionMode(QTableWidget.NoSelection)
|
||||
table.horizontalHeader().setStretchLastSection(True)
|
||||
for column, width in enumerate((260, 330, 300)):
|
||||
table.setColumnWidth(column, width)
|
||||
table.setVisible(False)
|
||||
|
||||
def toggled(shown):
|
||||
toggle.setArrowType(Qt.DownArrow if shown else Qt.RightArrow)
|
||||
table.setVisible(shown)
|
||||
toggle.toggled.connect(toggled)
|
||||
self.root.addWidget(toggle)
|
||||
self.root.addWidget(table, 1)
|
||||
|
||||
def accept(self):
|
||||
result = {}
|
||||
for key, text, action, device_type in self.rows:
|
||||
@@ -257,6 +291,8 @@ class PrintersPage(AccessPointsPage):
|
||||
key_func = staticmethod(printers.printer_key)
|
||||
mapping_header = "Drucker (IP, Modell, SNMP-Standort)"
|
||||
mapping_noun = "Drucker"
|
||||
mapping_options = {"empty_rows": "Ohne Standort und Mandant gilt der Standard-Standort mit seinem Mandanten; "
|
||||
"Drucker auslassen geht per Rechtsklick in der Tabelle."}
|
||||
|
||||
def __init__(self, window): # noqa: PLR0915 - builds the page
|
||||
Page.__init__(self, window)
|
||||
@@ -542,6 +578,17 @@ class PrintersPage(AccessPointsPage):
|
||||
("ap", self.key_func(printer)), self._placement(printer))
|
||||
for printer in sorted(new, key=lambda item: tuple(int(part) for part in item["ip"].split(".")))]
|
||||
|
||||
def _placement(self, printer):
|
||||
# Printers are left out via the context menu; a row without site and tenant
|
||||
# goes to the default site (with its tenant) instead of being dropped.
|
||||
return dict(super()._placement(printer), ignored=False)
|
||||
|
||||
def _tenant_for(self, placement):
|
||||
if placement.get("tenant") or placement.get("site") or not self.engine:
|
||||
return placement.get("tenant")
|
||||
site = next((row for row in self.engine.ap_sites if row["id"] == self.default_site.valid_data()), None)
|
||||
return (site or {}).get("tenant_id")
|
||||
|
||||
def _suggest_role(self, roles):
|
||||
return next((role_id for name, role_id in roles
|
||||
if any(hint in name.casefold() for hint in self.role_hints)), None)
|
||||
@@ -573,7 +620,9 @@ class PrintersPage(AccessPointsPage):
|
||||
return set(self._settings().get("ignored") or [])
|
||||
|
||||
def _model_decisions(self):
|
||||
return dict(self._settings().get("models") or {})
|
||||
# "create" (stored by older versions) is no longer offered and counts as undecided
|
||||
return {key: value for key, value in (self._settings().get("models") or {}).items()
|
||||
if value.get("action") in dict(MODEL_ACTIONS)}
|
||||
|
||||
def _model_action(self, printer):
|
||||
key = printers.model_key(printer)
|
||||
@@ -614,7 +663,16 @@ class PrintersPage(AccessPointsPage):
|
||||
decision["action"] = "skip"
|
||||
text = f"{first.get('manufacturer') or 'Unbekannt'} · {first.get('model') or '(kein Modell – nur Ports)'}"
|
||||
rows.append((text, len(members), key, decision, self.engine.suggest_type(first)))
|
||||
dialog = ModelMappingDialog(self.window, rows, self.engine.device_types)
|
||||
others = []
|
||||
for printer in self.aps:
|
||||
if printer.get("device") or self._excluded(printer):
|
||||
continue
|
||||
row = self.engine.existing_type(printer)
|
||||
if row:
|
||||
others.append((" · ".join(filter(None, (printer["name"], printer.get("ip")))),
|
||||
f"{printer.get('manufacturer') or ''} · {printer.get('model') or ''}",
|
||||
f"{row['manufacturer']} {row['model']}".strip()))
|
||||
dialog = ModelMappingDialog(self.window, rows, self.engine.device_types, others)
|
||||
if not dialog.exec():
|
||||
return False
|
||||
for key, value in dialog.result.items():
|
||||
@@ -688,8 +746,6 @@ class PrintersPage(AccessPointsPage):
|
||||
name = next((f"{row['manufacturer']} {row['model']}" for row in self.engine.device_types
|
||||
if row["id"] == decision.get("device_type")), "?")
|
||||
printer["issues"].append(f"Modell nicht in NetBox – wird als „{name}“ angelegt")
|
||||
elif decision.get("action") == "create":
|
||||
printer["issues"].append("Modell nicht in NetBox – Gerätetyp wird neu angelegt")
|
||||
else:
|
||||
printer["issues"].append("Modell nicht in NetBox – bitte unter „Modelle …“ entscheiden")
|
||||
super()._refresh()
|
||||
|
||||
+20
-2
@@ -126,6 +126,9 @@ def test_sync_creates_fields_and_printers_and_updates_counters(agent):
|
||||
known = to_import(dict(info, ip="10.20.0.60", snmp="SNMPv2c", notes=[], serial="", mac="",
|
||||
name="Drucker EG", page_count=200))
|
||||
nb = _netbox()
|
||||
nb.dcim.manufacturers.records.append(Record(nb.dcim.manufacturers, id=50, name="HP", slug="hp"))
|
||||
nb.dcim.device_types.records.append(Record(nb.dcim.device_types, id=61, model="Color LaserJet Pro M454dw",
|
||||
manufacturer=SimpleNamespace(id=50, name="HP")))
|
||||
engine = PrinterSyncEngine(nb, role_id=31)
|
||||
engine.load_context(7)
|
||||
items = [new, known]
|
||||
@@ -142,8 +145,8 @@ def test_sync_creates_fields_and_printers_and_updates_counters(agent):
|
||||
created = nb.dcim.devices.created[-1]
|
||||
assert created["name"] == "NPI1A2B3C" and created["serial"] == "VNB3K12345" and "platform" not in created
|
||||
assert created["custom_fields"]["printer_page_count"] == 48211 and created["custom_fields"]["printer_color"]
|
||||
assert nb.dcim.manufacturers.created[0]["name"] == "HP"
|
||||
assert nb.dcim.device_types.created[0]["model"] == "Color LaserJet Pro M454dw"
|
||||
assert created["device_type"] == 61
|
||||
assert nb.dcim.manufacturers.created == [] and nb.dcim.device_types.created == []
|
||||
assert nb.ipam.ip_addresses.created[-1]["address"] == f"{IP}/24"
|
||||
assert nb.dcim.devices.get(201).custom_fields["printer_page_count"] == 200
|
||||
|
||||
@@ -181,3 +184,18 @@ def test_missing_model_can_be_mapped_to_an_existing_device_type():
|
||||
report = engine.sync([printer], {printer_key(printer): {"site": 21, "tenant": 7}}, role_id=31, dry_run=False)
|
||||
assert report["errors"] == [] and nb.dcim.device_types.created == []
|
||||
assert nb.dcim.devices.created[-1]["device_type"] == 60
|
||||
|
||||
|
||||
def test_missing_device_type_is_never_created():
|
||||
nb = _netbox()
|
||||
printer = to_import({"ip": "10.20.0.71", "name": "Drucker25", "manufacturer": "Kyocera", "model": "ECOSYS M5526",
|
||||
"serial": "", "mac": "", "snmp": "SNMPv2c", "notes": []})
|
||||
engine = PrinterSyncEngine(nb, role_id=31, counters=False)
|
||||
engine.load_context(7)
|
||||
engine.match([printer])
|
||||
for dry_run in (True, False):
|
||||
report = engine.sync([printer], {printer_key(printer): {"site": 21, "tenant": 7}}, role_id=31,
|
||||
dry_run=dry_run, default_site=21)
|
||||
assert len(report["errors"]) == 1 and "fehlt in NetBox" in report["errors"][0]
|
||||
assert nb.dcim.manufacturers.created == [] and nb.dcim.device_types.created == []
|
||||
assert nb.dcim.devices.created == []
|
||||
@@ -679,3 +679,32 @@ def test_chosen_interface_of_another_device_is_ignored():
|
||||
assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] is None
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True)
|
||||
assert report["cables_created"] == 0
|
||||
|
||||
|
||||
def test_far_end_of_a_cable_gets_missing_vlans_of_the_switch_port():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.ipam.vlans.records += [
|
||||
Record(nb.ipam.vlans, id=120, vid=20, name="LAN", tenant=SimpleNamespace(id=7), site=None),
|
||||
Record(nb.ipam.vlans, id=136, vid=36, name="WMGMT", tenant=SimpleNamespace(id=7), site=None),
|
||||
]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [36], "tagged_all": False}
|
||||
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
|
||||
peer = nb.dcim.interfaces.get(20)
|
||||
peer.cable, peer.mode, peer.untagged_vlan, peer.tagged_vlans = SimpleNamespace(id=70), "access", 120, []
|
||||
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70,
|
||||
a_terminations=[{"object_type": "dcim.interface", "object_id": 2}],
|
||||
b_terminations=[{"object_type": "dcim.interface", "object_id": 20}]))
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert any("Gegenstelle" in change and "1 VLAN" in change for change in report["changes"])
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert peer.mode == "tagged" and peer.untagged_vlan == 120 and peer.tagged_vlans == [136]
|
||||
again = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert not any("Gegenstelle" in change for change in again["changes"])
|
||||
# VLAN 36 is removed on the switch: it disappears at the far end, too; a manual VLAN stays.
|
||||
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=199, vid=99, name="MANUELL", tenant=SimpleNamespace(id=7),
|
||||
site=None))
|
||||
peer.tagged_vlans = [136, 199]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [], "tagged_all": False}
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert any("1 VLAN(s) entfernt" in change for change in report["changes"])
|
||||
assert peer.untagged_vlan == 120 and peer.tagged_vlans == [199] and peer.mode == "tagged"
|
||||
Reference in new issue
Block a user