fix: printer default site and no automatic device type creation
- Load sites with the device roles so the default site can be chosen before the first scan - Printers without site and tenant in the mapping dialog go to the default site instead of being dropped - Never create printer device types or manufacturers; only existing or manually mapped types are used Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
b047278987
commit
698086a6aa
4 files changed
+73
-17
No files matched your search
@@ -398,6 +398,20 @@ class PrinterSyncEngine(APSyncEngine):
|
|||||||
def _mapped_type(self, printer):
|
def _mapped_type(self, printer):
|
||||||
return self.type_map.get(model_key(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):
|
def _known_devices(self, scope):
|
||||||
if not self.role_id:
|
if not self.role_id:
|
||||||
return []
|
return []
|
||||||
|
|||||||
@@ -48,11 +48,12 @@ 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, 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",
|
super().__init__(parent, "Standorte & Mandanten zuordnen",
|
||||||
f"Der Standort ist optional – {noun} ohne Zuordnung kommen an den Standard-Standort, weil NetBox "
|
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 "
|
"für jedes Gerät einen Standort verlangt. Der Mandant ist Pflicht und wird bewusst gewählt. "
|
||||||
"Standort und ohne Mandant werden ignoriert.",
|
+ empty_rows,
|
||||||
width=860)
|
width=860)
|
||||||
self.resize(980, 620)
|
self.resize(980, 620)
|
||||||
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
|
site_items = [("– kein Standort (Standard-Standort) –", 0)] + [
|
||||||
@@ -109,6 +110,7 @@ class AccessPointsPage(Page):
|
|||||||
key_func = staticmethod(ap_key)
|
key_func = staticmethod(ap_key)
|
||||||
mapping_header = "Sophos-Standort / Access Point"
|
mapping_header = "Sophos-Standort / Access Point"
|
||||||
mapping_noun = "APs"
|
mapping_noun = "APs"
|
||||||
|
mapping_options = {}
|
||||||
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, MAC und Name) und fehlende anlegen.")
|
"Seriennummer, MAC und Name) und fehlende anlegen.")
|
||||||
|
|
||||||
@@ -257,14 +259,23 @@ class AccessPointsPage(Page):
|
|||||||
|
|
||||||
def work(ctx):
|
def work(ctx):
|
||||||
nb = connect(ctx)
|
nb = connect(ctx)
|
||||||
ctx.log("Lade Geräterollen …")
|
ctx.log("Lade Geräterollen und Standorte …")
|
||||||
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())
|
||||||
|
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
|
self.roles = roles
|
||||||
settings = self._settings()
|
settings = self._settings()
|
||||||
role_id = settings.get("role_id") or self._suggest_role(roles)
|
role_id = settings.get("role_id") or self._suggest_role(roles)
|
||||||
self.role.set_items(roles, role_id)
|
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:
|
if then_compare:
|
||||||
QTimer.singleShot(0, self.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")
|
self.window.toast(f"Alle {self.noun} 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.mapping_header, self.mapping_noun)
|
self.mapping_header, self.mapping_noun, **self.mapping_options)
|
||||||
if not dialog.exec():
|
if not dialog.exec():
|
||||||
return False
|
return False
|
||||||
settings = self._settings()
|
settings = self._settings()
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ from netbox_sync.ui.widgets import (
|
|||||||
label,
|
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"))
|
("skip", "Diesmal überspringen"), ("ignore", "Dauerhaft ignorieren"))
|
||||||
AUTH_CHOICES = ["", *snmp.AUTH_PROTOCOLS]
|
AUTH_CHOICES = ["", *snmp.AUTH_PROTOCOLS]
|
||||||
PRIV_CHOICES = ["", *snmp.PRIV_PROTOCOLS]
|
PRIV_CHOICES = ["", *snmp.PRIV_PROTOCOLS]
|
||||||
@@ -196,9 +196,9 @@ class ModelMappingDialog(_Dialog):
|
|||||||
|
|
||||||
def __init__(self, parent, rows, device_types):
|
def __init__(self, parent, rows, device_types):
|
||||||
super().__init__(parent, "Modelle zuordnen",
|
super().__init__(parent, "Modelle zuordnen",
|
||||||
"Diese Modelle gibt es in NetBox noch nicht als Gerätetyp. Pro Modell: neu anlegen, einen "
|
"Diese Modelle gibt es in NetBox nicht als Gerätetyp. Gerätetypen werden nicht automatisch "
|
||||||
"vorhandenen Gerätetyp verwenden, die Drucker dieses Modells diesmal überspringen oder dauerhaft "
|
"angelegt – pro Modell einen vorhandenen Gerätetyp wählen, die Drucker dieses Modells diesmal "
|
||||||
"ignorieren (gespeichert im Profil).", width=900)
|
"überspringen oder dauerhaft ignorieren (gespeichert im Profil).", width=900)
|
||||||
self.resize(1040, 520)
|
self.resize(1040, 520)
|
||||||
type_items = [(f"{row['manufacturer']} {row['model']}".strip(), row["id"]) for row in device_types]
|
type_items = [(f"{row['manufacturer']} {row['model']}".strip(), row["id"]) for row in device_types]
|
||||||
self.table = QTableWidget(0, 4)
|
self.table = QTableWidget(0, 4)
|
||||||
@@ -214,7 +214,7 @@ class ModelMappingDialog(_Dialog):
|
|||||||
action.addItem(caption, value)
|
action.addItem(caption, value)
|
||||||
device_type = SearchableComboBox("Gerätetyp suchen …")
|
device_type = SearchableComboBox("Gerätetyp suchen …")
|
||||||
device_type.set_items(type_items, decision.get("device_type") or suggestion)
|
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.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"))
|
action.currentIndexChanged.connect(lambda _i, a=action, d=device_type: d.setEnabled(a.currentData() == "map"))
|
||||||
device_type.setEnabled(chosen == "map")
|
device_type.setEnabled(chosen == "map")
|
||||||
@@ -257,6 +257,8 @@ class PrintersPage(AccessPointsPage):
|
|||||||
key_func = staticmethod(printers.printer_key)
|
key_func = staticmethod(printers.printer_key)
|
||||||
mapping_header = "Drucker (IP, Modell, SNMP-Standort)"
|
mapping_header = "Drucker (IP, Modell, SNMP-Standort)"
|
||||||
mapping_noun = "Drucker"
|
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
|
def __init__(self, window): # noqa: PLR0915 - builds the page
|
||||||
Page.__init__(self, window)
|
Page.__init__(self, window)
|
||||||
@@ -542,6 +544,17 @@ class PrintersPage(AccessPointsPage):
|
|||||||
("ap", self.key_func(printer)), self._placement(printer))
|
("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(".")))]
|
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):
|
def _suggest_role(self, roles):
|
||||||
return next((role_id for name, role_id in roles
|
return next((role_id for name, role_id in roles
|
||||||
if any(hint in name.casefold() for hint in self.role_hints)), None)
|
if any(hint in name.casefold() for hint in self.role_hints)), None)
|
||||||
@@ -573,7 +586,9 @@ class PrintersPage(AccessPointsPage):
|
|||||||
return set(self._settings().get("ignored") or [])
|
return set(self._settings().get("ignored") or [])
|
||||||
|
|
||||||
def _model_decisions(self):
|
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):
|
def _model_action(self, printer):
|
||||||
key = printers.model_key(printer)
|
key = printers.model_key(printer)
|
||||||
@@ -688,8 +703,6 @@ class PrintersPage(AccessPointsPage):
|
|||||||
name = next((f"{row['manufacturer']} {row['model']}" for row in self.engine.device_types
|
name = next((f"{row['manufacturer']} {row['model']}" for row in self.engine.device_types
|
||||||
if row["id"] == decision.get("device_type")), "?")
|
if row["id"] == decision.get("device_type")), "?")
|
||||||
printer["issues"].append(f"Modell nicht in NetBox – wird als „{name}“ angelegt")
|
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:
|
else:
|
||||||
printer["issues"].append("Modell nicht in NetBox – bitte unter „Modelle …“ entscheiden")
|
printer["issues"].append("Modell nicht in NetBox – bitte unter „Modelle …“ entscheiden")
|
||||||
super()._refresh()
|
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="",
|
known = to_import(dict(info, ip="10.20.0.60", snmp="SNMPv2c", notes=[], serial="", mac="",
|
||||||
name="Drucker EG", page_count=200))
|
name="Drucker EG", page_count=200))
|
||||||
nb = _netbox()
|
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 = PrinterSyncEngine(nb, role_id=31)
|
||||||
engine.load_context(7)
|
engine.load_context(7)
|
||||||
items = [new, known]
|
items = [new, known]
|
||||||
@@ -142,8 +145,8 @@ def test_sync_creates_fields_and_printers_and_updates_counters(agent):
|
|||||||
created = nb.dcim.devices.created[-1]
|
created = nb.dcim.devices.created[-1]
|
||||||
assert created["name"] == "NPI1A2B3C" and created["serial"] == "VNB3K12345" and "platform" not in created
|
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 created["custom_fields"]["printer_page_count"] == 48211 and created["custom_fields"]["printer_color"]
|
||||||
assert nb.dcim.manufacturers.created[0]["name"] == "HP"
|
assert created["device_type"] == 61
|
||||||
assert nb.dcim.device_types.created[0]["model"] == "Color LaserJet Pro M454dw"
|
assert nb.dcim.manufacturers.created == [] and nb.dcim.device_types.created == []
|
||||||
assert nb.ipam.ip_addresses.created[-1]["address"] == f"{IP}/24"
|
assert nb.ipam.ip_addresses.created[-1]["address"] == f"{IP}/24"
|
||||||
assert nb.dcim.devices.get(201).custom_fields["printer_page_count"] == 200
|
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)
|
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 report["errors"] == [] and nb.dcim.device_types.created == []
|
||||||
assert nb.dcim.devices.created[-1]["device_type"] == 60
|
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 == []
|
||||||
Reference in new issue
Block a user