Compare commits

...
4 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 8464895b06 chore: release 4.7.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:36:18 +01:00
MrBlakeandClaude Opus 5.5 e499d854a9 feat: tenant group VRFs for switch networks, remembered network decisions, in-app updates
- Networks tab offers the VRFs of the switch's tenant group and finds
  existing prefixes there; network decisions are stored per profile and
  shared by all switches (per-switch choices are migrated)
- Decided networks and VLANs sit in a collapsed, editable section
- Check the Gitea releases on start (or on demand in the settings); after
  confirmation the installer runs silently and restarts the application, the
  portable EXE swaps itself; a version can be skipped
- Installer restarts the application after a silent update

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 15:36:17 +01:00
MrBlakeandClaude Opus 5.5 3db5e83f0a chore: release 4.6.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:33:14 +01:00
MrBlakeandClaude Opus 5.5 3df4e6a9fc feat: ignore switch VLANs and remember VLAN decisions per profile
- New "ignore" choice: the VLAN is neither created nor assigned and is left
  out of interface labels and the VLAN column
- VLAN decisions are stored once per profile and shared by all switches;
  per-switch decisions from 4.5.0 are migrated on load
- Review dialog shows one row per VID; only open VLANs are listed, stored and
  unambiguous ones sit in a collapsed, editable section

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:33:14 +01:00
15 changed files with 756 additions and 142 deletions

No files matched your search

+13 -3
View File
@@ -22,6 +22,10 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- Log with filter, search and export, plus a rotating log file under - Log with filter, search and export, plus a rotating log file under
`%APPDATA%\NetBox VM Import\logs` `%APPDATA%\NetBox VM Import\logs`
- Keyboard shortcuts: `Ctrl+1…8` navigation, `F5` reload/read, `Ctrl+F` search - Keyboard shortcuts: `Ctrl+1…8` navigation, `F5` reload/read, `Ctrl+F` search
- Updates from the Gitea releases: checked on start (can be switched off in the
settings, or run on demand); after confirmation the installed version runs the
new setup silently and the portable EXE replaces itself, then the application
restarts. A version can be skipped
### Virtual machines ### Virtual machines
@@ -62,13 +66,19 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
- **Mapping review** before the preview: non-obvious port mappings and every - **Mapping review** before the preview: non-obvious port mappings and every
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
any device of the switch's tenant group. Choices are stored in the profile any device of the switch's tenant group. Choices are stored in the profile
- Networks and VLANs in the same review: per network the VRF (global, a tenant - Networks and VLANs in the same review: per network the VRF (global, a VRF of
VRF or a new one) and whether a missing prefix is created the tenant group or a new one) and whether a missing prefix is created. Network
decisions are stored per profile like the VLAN decisions; networks whose
prefix exists or that were decided before sit in a collapsed, editable section
- VLAN mapping: switch VLANs are matched to NetBox VLANs of the switch's tenant - VLAN mapping: switch VLANs are matched to NetBox VLANs of the switch's tenant
group by VID (own tenant, site and similar names decide between several); group by VID (own tenant, site and similar names decide between several);
each VLAN can be mapped manually, skipped or created with a name and a tenant each VLAN can be mapped manually, skipped or created with a name and a tenant
of the tenant group of your choice (pre-filled from the switch configuration of the tenant group of your choice (pre-filled from the switch configuration
and the switch's tenant). Mapped VLANs are assigned and the switch's tenant). VLANs can also be **ignored** on all switches –
they are neither created nor assigned and are left out of the labels. VLAN
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)
- Tenant required: a switch without tenant in NetBox is refused; every created - Tenant required: a switch without tenant in NetBox is refused; every created
IP address, prefix, VRF, VLAN and cable gets the switch's tenant IP address, prefix, VRF, VLAN and cable gets the switch's tenant
+3 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.5.0" #define AppVersion "4.7.0"
#endif #endif
#define AppPublisher "Louis-Alexander Kerst" #define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe" #define AppExeName "NetBoxSynchronizer.exe"
@@ -66,6 +66,8 @@ Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExeName}"; AppUserModelI
[Run] [Run]
Filename: "{app}\{#AppExeName}"; Description: "{cm:LaunchProgram,{#AppName}}"; Flags: nowait postinstall skipifsilent Filename: "{app}\{#AppExeName}"; Description: "{cm:LaunchProgram,{#AppName}}"; Flags: nowait postinstall skipifsilent
; Restart after an update started from within the application (silent mode).
Filename: "{app}\{#AppExeName}"; Flags: nowait; Check: WizardSilent
[Code] [Code]
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
+1 -1
View File
@@ -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.5.0" APP_VERSION = "4.7.0"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+19
View File
@@ -21,6 +21,8 @@ DEFAULT_SETTINGS = {
"create_cables": True, "create_cables": True,
"offline_mode": False, # collect and export to JSON without NetBox "offline_mode": False, # collect and export to JSON without NetBox
"parallel_wmi": 8, # concurrent WinRM sessions for client scans "parallel_wmi": 8, # concurrent WinRM sessions for client scans
"auto_update_check": True, # look for a newer Gitea release on start
"skipped_version": "", # release the user chose to skip
} }
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -116,6 +118,10 @@ def empty_profile(name):
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name. # Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {}, "cluster_map": {},
"host_map": {}, "host_map": {},
# Switch VLAN decisions for all switches: "<vid>" -> {"action": "map"|"new"|"skip"|"ignore", ...}.
"vlan_map": {},
# Switch network decisions: "<network>" -> {"vrf_id", "vrf_name" (new VRF), "create": prefix}.
"network_map": {},
# Windows client scan: targets and options, never a password. # Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS), "clients": dict(DEFAULT_CLIENT_OPTIONS),
} }
@@ -164,6 +170,8 @@ class ProfileStore:
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))), "netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})), "cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})), "host_map": dict(record.get("host_map", {})),
"vlan_map": dict(record.get("vlan_map", {})),
"network_map": dict(record.get("network_map", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items() "clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}}, if key in DEFAULT_CLIENT_OPTIONS}},
}) })
@@ -171,6 +179,15 @@ class ProfileStore:
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}")) profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for switch in record.get("switches", []): for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}")) profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from 4.5/4.6: VLAN and network decisions were stored per switch.
for switch in profile["switches"]:
for vid, choice in (switch.pop("vlan_map", None) or {}).items():
profile["vlan_map"].setdefault(vid, choice)
switch.pop("create_vlans", None)
approved = switch.pop("create_prefixes", None) or []
for network, vrf_name in (switch.pop("network_vrfs", None) or {}).items():
profile["network_map"].setdefault(network, {"vrf_id": None, "vrf_name": vrf_name or "",
"create": network in approved})
# Migration from v2: one VMware source embedded in each profile. # Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"): if not profile["sources"] and record.get("esxi_host"):
@@ -228,6 +245,8 @@ class ProfileStore:
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])], "switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})), "cluster_map": dict(profile.get("cluster_map", {})),
"host_map": dict(profile.get("host_map", {})), "host_map": dict(profile.get("host_map", {})),
"vlan_map": dict(profile.get("vlan_map", {})),
"network_map": dict(profile.get("network_map", {})),
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)), "clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
}) })
+99 -34
View File
@@ -1075,9 +1075,23 @@ VLAN_METHODS = {
"manual": "manuell", "manual": "manuell",
"new": "fehlt", "new": "fehlt",
"skip": "nicht zuordnen", "skip": "nicht zuordnen",
"ignore": "ignoriert",
} }
def ignored_vlans(vlan_map):
"""VLAN IDs the user chose to ignore on all switches of the profile."""
return {int(vid) for vid, choice in (vlan_map or {}).items() if (choice or {}).get("action") == "ignore"}
def without_vlans(vlans, ignored):
"""Port VLAN membership without ignored VLANs (``None`` stays ``None``)."""
if not vlans or not ignored:
return vlans
return dict(vlans, untagged=[vid for vid in vlans.get("untagged", []) if vid not in ignored],
tagged=[vid for vid in vlans.get("tagged", []) if vid not in ignored])
def candidate_vlans(nb, tenant_id): def candidate_vlans(nb, tenant_id):
"""VLANs of the switch's tenant group (or tenant) – a VLAN may belong to a """VLANs of the switch's tenant group (or tenant) – a VLAN may belong to a
sibling tenant, e.g. a school network documented under its own tenant.""" sibling tenant, e.g. a school network documented under its own tenant."""
@@ -1134,8 +1148,8 @@ def match_vlans(vids, names, vlans, tenant_id, site_id, manual=None):
created = next((vlan for vlan in by_vid.get(vid, []) if vlan.name.casefold() == name.casefold()), None) created = next((vlan for vlan in by_vid.get(vid, []) if vlan.name.casefold() == name.casefold()), None)
result[vid] = (created, "manual", name) if created else (None, "new", name) result[vid] = (created, "manual", name) if created else (None, "new", name)
continue continue
if choice.get("action") == "skip": if choice.get("action") in ("skip", "ignore"):
result[vid] = (None, "skip", switch_name) result[vid] = (None, choice["action"], switch_name)
continue continue
if choice.get("action") == "map" and choice.get("id") in by_id: if choice.get("action") == "map" and choice.get("id") in by_id:
result[vid] = (by_id[choice["id"]], "manual", switch_name) result[vid] = (by_id[choice["id"]], "manual", switch_name)
@@ -1196,24 +1210,24 @@ def plan_switch_sync(nb, config, snapshot):
neighbors.append(dict(neighbor, device_id=device_id, method=method)) neighbors.append(dict(neighbor, device_id=device_id, method=method))
devices.sort(key=lambda row: row["name"].casefold()) devices.sort(key=lambda row: row["name"].casefold())
tenant_vrfs = {vrf.id: vrf.name for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)} vrf_records = candidate_vrfs(nb, tenant_id)
vrfs = sorted(tenant_vrfs.values(), key=str.casefold) vrfs = [{"id": vrf.id, "label": vrf_choice_label(vrf)}
stored_vrfs = config.get("network_vrfs") or {} for vrf in sorted(vrf_records, key=lambda item: (item.name or "").casefold())]
create_prefixes = config.get("create_prefixes")
networks = [] networks = []
for network in snapshot_networks(snapshot): for network in snapshot_networks(snapshot):
# Where the prefix already exists: "" = global, otherwise a tenant VRF. # Where the prefix already exists: 0 = global, otherwise a VRF of the tenant group.
existing = set() existing = sorted({related_id(prefix, "vrf") or 0 for prefix in nb.ipam.prefixes.filter(prefix=network)}
for prefix in nb.ipam.prefixes.filter(prefix=network): & ({0} | {vrf.id for vrf in vrf_records}), key=lambda value: (value == 0, value))
vrf_id = related_id(prefix, "vrf") choice = _network_choice(config, network)
if vrf_id is None or vrf_id in tenant_vrfs: if choice is not None:
existing.add(tenant_vrfs.get(vrf_id, "")) vrf_id = _resolve_vrf_choice(choice, vrf_records, tenant_id)
existing = sorted(existing) vrf_id = vrf_id if isinstance(vrf_id, int) else 0
vrf = stored_vrfs[network] if network in stored_vrfs else (existing[0] if existing else "") networks.append({"network": network, "vrf_id": vrf_id,
if vrf and vrf not in vrfs: "vrf_name": choice.get("vrf_name") if not vrf_id else "",
vrfs.append(vrf) # chosen earlier as new VRF, not created yet "existing": existing, "create": bool(choice.get("create")), "stored": True})
networks.append({"network": network, "vrf": vrf, "existing_vrfs": existing, else:
"create": create_prefixes is None or network in create_prefixes}) networks.append({"network": network, "vrf_id": existing[0] if existing else 0, "vrf_name": "",
"existing": existing, "create": True, "stored": False})
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()} names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
candidates, vlan_matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, related_id(device, "site")) candidates, vlan_matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, related_id(device, "site"))
@@ -1225,6 +1239,7 @@ def plan_switch_sync(nb, config, snapshot):
new_tenant = (vlan_map.get(str(vid)) or {}).get("tenant") new_tenant = (vlan_map.get(str(vid)) or {}).get("tenant")
vlans.append({ vlans.append({
"vid": vid, "name": names.get(vid) or f"VLAN{vid}", "method": method, "new_name": new_name, "vid": vid, "name": names.get(vid) or f"VLAN{vid}", "method": method, "new_name": new_name,
"stored": str(vid) in vlan_map,
"new_tenant": new_tenant if new_tenant in allowed else tenant_id, "new_tenant": new_tenant if new_tenant in allowed else tenant_id,
"netbox_id": record.id if record else None, "netbox_id": record.id if record else None,
"candidates": [{"id": vlan.id, "label": vlan_choice_label(vlan)} "candidates": [{"id": vlan.id, "label": vlan_choice_label(vlan)}
@@ -1236,7 +1251,8 @@ def plan_switch_sync(nb, config, snapshot):
"device": {"id": device.id, "name": device.name}, "device": {"id": device.id, "name": device.name},
"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), "vlan_label": vlan_label(item.get("vlans"))} "physical": _physical_interface(item),
"vlan_label": vlan_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
for item in snapshot["interfaces"] for item in snapshot["interfaces"]
for record, method in [matches[item["name"]]] for record, method in [matches[item["name"]]]
], ],
@@ -1305,33 +1321,80 @@ class _RemoteLookup:
_NEW = "new" # placeholder ID of objects a dry run would create _NEW = "new" # placeholder ID of objects a dry run would create
def candidate_vrfs(nb, tenant_id):
"""VRFs of the switch's tenant and of its tenant group."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
found = {vrf.id: vrf for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)}
if group_id:
found.update({vrf.id: vrf for vrf in nb.ipam.vrfs.filter(tenant_group_id=group_id)})
return list(found.values())
def vrf_choice_label(vrf):
owner = getattr(getattr(vrf, "tenant", None), "name", None)
return vrf.name + (f" ({owner})" if owner else "")
def _network_choice(config, network):
"""Stored decision ``{"vrf_id", "vrf_name", "create"}`` for a network, or ``None``."""
choice = (config.get("network_map") or {}).get(network)
if choice is not None:
return choice
# Profiles up to 4.6.0 stored a VRF name and approved prefixes per switch.
legacy_vrfs, legacy_create = config.get("network_vrfs") or {}, config.get("create_prefixes")
if network not in legacy_vrfs and legacy_create is None:
return None
return {"vrf_id": None, "vrf_name": legacy_vrfs.get(network) or "", "create": network in (legacy_create or [])}
def _resolve_vrf_choice(choice, vrf_records, tenant_id):
"""Existing VRF ID, ``None`` for global or the name of a VRF still to create."""
by_id = {vrf.id: vrf for vrf in vrf_records}
if choice.get("vrf_id") in by_id:
return choice["vrf_id"]
name = (choice.get("vrf_name") or "").strip()
if not name:
return None
named = sorted((vrf for vrf in vrf_records if vrf.name.casefold() == name.casefold()),
key=lambda vrf: related_id(vrf, "tenant") != tenant_id)
return named[0].id if named else name
def _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report): def _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report):
"""``{network: VRF ID or None}``; VRFs chosen by name are created for the tenant.""" """``{network: VRF ID or None}``; new VRFs are created for the switch's tenant."""
by_name = {vrf.name: vrf.id for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)} vrf_records = candidate_vrfs(nb, tenant_id)
chosen = config.get("network_vrfs") or {} created = {}
result = {} result = {}
for network in snapshot_networks(snapshot): for network in snapshot_networks(snapshot):
name = chosen.get(network) or "" choice = _network_choice(config, network) or {}
if name and name not in by_name: resolved = _resolve_vrf_choice(choice, vrf_records, tenant_id)
report["vrfs_created"] += 1 if isinstance(resolved, str):
report["changes"].append(f"VRF {name} neu") if resolved not in created:
by_name[name] = _NEW if dry_run else nb.ipam.vrfs.create({"name": name, "tenant": tenant_id}).id report["vrfs_created"] += 1
result[network] = by_name[name] if name else None report["changes"].append(f"VRF {resolved} neu")
created[resolved] = _NEW if dry_run else nb.ipam.vrfs.create({"name": resolved, "tenant": tenant_id}).id
resolved = created[resolved]
result[network] = resolved
return result return result
def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report): def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
"""Create missing prefixes that were approved; existing ones stay untouched.""" """Create missing prefixes that were approved; existing ones stay untouched."""
approved = set(config.get("create_prefixes") or [])
for network in snapshot_networks(snapshot): for network in snapshot_networks(snapshot):
vrf_id = vrf_ids.get(network) vrf_id = vrf_ids.get(network)
if network not in approved: if not (_network_choice(config, network) or {}).get("create"):
continue continue
if vrf_id != _NEW and list(nb.ipam.prefixes.filter(prefix=network, vrf_id=vrf_id or "null")): if vrf_id != _NEW and list(nb.ipam.prefixes.filter(prefix=network, vrf_id=vrf_id or "null")):
continue continue
try: try:
report["prefixes_created"] += 1 report["prefixes_created"] += 1
vrf_name = (config.get("network_vrfs") or {}).get(network) or "global" if not vrf_id:
vrf_name = "global"
elif vrf_id == _NEW:
vrf_name = f"VRF {_network_choice(config, network).get('vrf_name')}"
else:
vrf_name = f"VRF {getattr(nb.ipam.vrfs.get(vrf_id), 'name', vrf_id)}"
report["changes"].append(f"Prefix {network} neu ({vrf_name})") report["changes"].append(f"Prefix {network} neu ({vrf_name})")
if not dry_run: if not dry_run:
nb.ipam.prefixes.create({"prefix": network, "status": "active", "tenant": tenant_id, "vrf": vrf_id}) nb.ipam.prefixes.create({"prefix": network, "status": "active", "tenant": tenant_id, "vrf": vrf_id})
@@ -1425,6 +1488,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
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_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report)
ignored = ignored_vlans(config.get("vlan_map"))
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)), matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
config.get("interface_map")) config.get("interface_map"))
records = {} records = {}
@@ -1432,7 +1496,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
for interface in snapshot["interfaces"]: for interface in snapshot["interfaces"]:
key = interface_key(interface["name"]) key = interface_key(interface["name"])
record, method = matches[interface["name"]] record, method = matches[interface["name"]]
label = vlan_label(interface.get("vlans")) port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
label = vlan_label(port["vlans"])
try: try:
if record: if record:
changes = {} changes = {}
@@ -1442,7 +1507,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(interface, vlan_ids, record)) changes.update(_vlan_assignment(port, vlan_ids, record))
if changes: if changes:
report["interfaces_updated"] += 1 report["interfaces_updated"] += 1
texts = [] texts = []
@@ -1467,7 +1532,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(interface, vlan_ids)) payload.update(_vlan_assignment(port, vlan_ids))
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
+143
View File
@@ -0,0 +1,143 @@
"""Updates from the Gitea releases of the project.
The latest release is read anonymously from the Gitea API. The installed
version updates by running the new installer silently (it restarts the
application afterwards); the portable EXE is swapped in place: Windows allows
renaming a running EXE, so the old file is moved aside and removed on the next
start.
"""
import re
import subprocess
import sys
from pathlib import Path
import requests
from netbox_sync import APP_VERSION
REPOSITORY_API = "https://git.mrblake.cc/api/v1/repos/MrBlake/NetBox-Import-Desktop"
LATEST_RELEASE_URL = f"{REPOSITORY_API}/releases/latest"
PORTABLE_ASSET = "NetBox VM Import.exe"
INSTALLER_ASSET = re.compile(r"(?i)^NetBoxSynchronizer-Setup-[\d.]+\.exe$")
INSTALLER_ARGUMENTS = ("/SILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/CLOSEAPPLICATIONS")
_DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
class UpdateError(RuntimeError):
pass
def parse_version(text):
"""``"v4.6.0"`` → ``(4, 6, 0)``."""
numbers = [int(part) for part in re.findall(r"\d+", text or "")[:3]]
return tuple(numbers + [0] * (3 - len(numbers)))
def install_kind():
"""``"installer"``, ``"portable"`` or ``None`` when running from source."""
if not getattr(sys, "frozen", False):
return None
exe_dir = Path(sys.executable).resolve().parent
bundle = Path(getattr(sys, "_MEIPASS", exe_dir)).resolve()
# A one-file (portable) build unpacks itself into a temporary folder.
return "installer" if bundle == exe_dir or exe_dir in bundle.parents else "portable"
def check_for_update(current=APP_VERSION, timeout=10):
"""Return the newer release or ``None``."""
try:
response = requests.get(LATEST_RELEASE_URL, timeout=timeout, headers={"Accept": "application/json"})
response.raise_for_status()
release = response.json()
except (requests.RequestException, ValueError) as error:
raise UpdateError(f"Update-Server nicht erreichbar: {error}") from error
if release.get("draft") or release.get("prerelease"):
return None
tag = release.get("tag_name") or ""
if parse_version(tag) <= parse_version(current):
return None
return {
"version": tag.lstrip("vV"),
"name": release.get("name") or tag,
"notes": release.get("body") or "",
"page": release.get("html_url") or "",
"assets": {asset["name"]: {"url": asset["browser_download_url"], "size": int(asset.get("size") or 0)}
for asset in release.get("assets", []) if asset.get("browser_download_url")},
}
def pick_asset(release, kind):
"""``(name, asset)`` matching the running installation, or ``None``."""
for name, asset in release["assets"].items():
if kind == "portable" and name.casefold() == PORTABLE_ASSET.casefold():
return name, asset
if kind == "installer" and INSTALLER_ASSET.match(name):
return name, asset
return None
def download(asset, target, progress=None, cancelled=None, timeout=30):
"""Stream ``asset`` to ``target``; the size is verified before the file is kept."""
target = Path(target)
partial = target.with_name(target.name + ".part")
try:
with requests.get(asset["url"], stream=True, timeout=timeout) as response:
response.raise_for_status()
total = asset.get("size") or int(response.headers.get("Content-Length") or 0)
done = 0
with partial.open("wb") as handle:
for chunk in response.iter_content(256 * 1024):
if cancelled and cancelled():
raise UpdateError("Download abgebrochen.")
handle.write(chunk)
done += len(chunk)
if progress:
progress(done, total)
except requests.RequestException as error:
partial.unlink(missing_ok=True)
raise UpdateError(f"Download fehlgeschlagen: {error}") from error
except BaseException:
partial.unlink(missing_ok=True)
raise
if total and done != total:
partial.unlink(missing_ok=True)
raise UpdateError(f"Download unvollständig ({done} von {total} Bytes).")
partial.replace(target)
return target
def portable_download_path():
exe = Path(sys.executable)
return exe.with_name(exe.stem + ".new.exe")
def apply_portable(new_exe):
"""Swap the running portable EXE for ``new_exe`` and start it."""
exe = Path(sys.executable)
old = exe.with_name(exe.stem + ".old.exe")
old.unlink(missing_ok=True)
exe.replace(old)
try:
Path(new_exe).replace(exe)
except OSError:
old.replace(exe)
raise
subprocess.Popen([str(exe)], close_fds=True, creationflags=_DETACHED) # noqa: S603
def apply_installer(setup_exe):
"""Run the installer silently; it closes and restarts the application."""
subprocess.Popen([str(setup_exe), *INSTALLER_ARGUMENTS], close_fds=True, creationflags=_DETACHED) # noqa: S603
def remove_leftovers():
"""Delete the previous portable EXE left behind by an update."""
if install_kind() != "portable":
return
exe = Path(sys.executable)
for leftover in (exe.with_name(exe.stem + ".old.exe"), portable_download_path()):
try:
leftover.unlink(missing_ok=True)
except OSError:
pass
+16 -2
View File
@@ -405,7 +405,11 @@ 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}
items = [(dict(by_id[switch_id]), self.state.switch_snapshots[switch_id]) # VLAN and network decisions are shared by all switches of the profile.
vlan_map = self.state.profile.setdefault("vlan_map", {})
network_map = self.state.profile.setdefault("network_map", {})
items = [(dict(by_id[switch_id], vlan_map=dict(vlan_map), network_map=dict(network_map)),
self.state.switch_snapshots[switch_id])
for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots] for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots]
if not items: if not items:
widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info") widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info")
@@ -429,7 +433,8 @@ class Actions:
needs_review = any( needs_review = any(
any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"]) any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"])
for entry in item["interfaces"]) or (create_cables and item["neighbors"]) for entry in item["interfaces"]) or (create_cables and item["neighbors"])
or item["networks"] or any(vlan["method"] != "vid" for vlan in item["vlans"]) or any(not network["stored"] and not network["existing"] for network in item["networks"])
or any(not vlan["stored"] and vlan["method"] in ("new", "ambiguous") for vlan in item["vlans"])
for _switch, item in reviewable) for _switch, item in reviewable)
def ask(): def ask():
@@ -440,13 +445,22 @@ class Actions:
if not dialog.exec(): if not dialog.exec():
return return
stored = {switch["id"]: switch for switch in self.state.switches} stored = {switch["id"]: switch for switch in self.state.switches}
vlan_map.clear()
vlan_map.update(dialog.vlan_map)
network_map.clear()
network_map.update(dialog.network_map)
for switch, _snapshot in items: for switch, _snapshot in items:
choices = dialog.result.get(switch["id"]) choices = dialog.result.get(switch["id"])
if choices: if choices:
switch.update(choices) switch.update(choices)
if switch["id"] in stored: if switch["id"] in stored:
stored[switch["id"]].update(choices) stored[switch["id"]].update(choices)
switch.update(vlan_map=dict(vlan_map), network_map=dict(network_map))
for legacy in ("network_vrfs", "create_prefixes", "create_vlans"):
switch.pop(legacy, None)
stored.get(switch["id"], {}).pop(legacy, None)
self.state.touch() self.state.touch()
self.state.switches_changed.emit() # ignored VLANs vanish from the VLAN column
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch", self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
on_success=show_preview, on_error=self._netbox_failed) on_success=show_preview, on_error=self._netbox_failed)
QTimer.singleShot(0, ask) QTimer.singleShot(0, ask)
+1
View File
@@ -84,6 +84,7 @@ def main():
hints.colorSchemeChanged.connect(lambda _scheme: theme.mode == "system" and theme.apply()) hints.colorSchemeChanged.connect(lambda _scheme: theme.mode == "system" and theme.apply())
install_excepthook(lambda: window) install_excepthook(lambda: window)
window.show() window.show()
window.updates.check_on_start()
return app.exec() return app.exec()
+188 -94
View File
@@ -590,6 +590,12 @@ class SwitchMappingDialog(_Dialog):
self.resize(1120, 680) self.resize(1120, 680)
self.plans = plans self.plans = plans
self.result = None self.result = None
# Profile-wide VLAN decisions; every switch config carries the same map.
self.previous_vlan_map = dict((plans[0][0].get("vlan_map") if plans else None) or {})
self.vlan_map = dict(self.previous_vlan_map)
self.previous_network_map = dict((plans[0][0].get("network_map") if plans else None) or {})
self.network_map = dict(self.previous_network_map)
self._new_vrf_names = []
tabs = QTabWidget() tabs = QTabWidget()
# Interfaces -------------------------------------------------------- # Interfaces --------------------------------------------------------
@@ -662,96 +668,73 @@ class SwitchMappingDialog(_Dialog):
tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)") tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)")
# Networks -------------------------------------------------------------- # Networks --------------------------------------------------------------
# Network decisions apply to all switches of the profile: one row per network.
self.network_rows = [] self.network_rows = []
networks = [(switch, plan, item) for switch, plan in plans for item in plan["networks"]] networks = {}
for switch, plan in plans:
for item in plan["networks"]:
entry = networks.setdefault(item["network"], {"item": item, "switches": [], "tenants": [], "vrfs": {}})
entry["switches"].append(switch["name"])
if plan["tenant"] not in entry["tenants"]:
entry["tenants"].append(plan["tenant"])
entry["vrfs"].update({vrf["id"]: vrf["label"] for vrf in plan["vrfs"]})
if networks: if networks:
network_page = QWidget() network_page = QWidget()
network_layout = QVBoxLayout(network_page) network_layout = QVBoxLayout(network_page)
network_layout.setContentsMargins(0, 12, 0, 0) network_layout.setContentsMargins(0, 12, 0, 0)
network_layout.addWidget(label( network_layout.addWidget(label(
"Netze der Switch-IP-Adressen. Die VRF gilt für Prefix und IP-Adressen; zur Auswahl stehen die " "Netze der Switch-IP-Adressen. Die VRF gilt für Prefix und IP-Adressen; zur Auswahl stehen die "
"globale Tabelle und die VRFs des Mandanten. Fehlende Prefixe werden nur angelegt, wenn sie " "globale Tabelle und die VRFs der Mandantengruppe. Fehlende Prefixe werden nur angelegt, wenn sie "
"angehakt sind – immer mit dem Mandanten des Switches.", muted=True, wrap=True)) "angehakt sind – mit dem Mandanten des Switches. Die Auswahl gilt für alle Switche des Profils.",
self.network_table = QTableWidget(0, 5) muted=True, wrap=True))
self.network_table.setHorizontalHeaderLabels(["Switch", "Mandant", "Netz", "VRF", "Prefix in NetBox"]) settled = {network: entry["item"]["stored"] or bool(entry["item"]["existing"])
for switch, plan, item in networks: for network, entry in networks.items()}
row = self.network_table.rowCount() self.open_network_table = self._network_table()
self.network_table.insertRow(row) self.settled_network_table = self._network_table()
combo = QComboBox() for network, entry in networks.items():
combo.addItem("Global (keine VRF)", "") table = self.settled_network_table if settled[network] else self.open_network_table
for name in plan["vrfs"]: self._add_network_row(table, entry)
combo.addItem(name, name) for table in (self.open_network_table, self.settled_network_table):
combo.addItem("+ Neue VRF …", self.NEW) self._prepare_table(table, (160, 150, 150, 300, 200))
combo.setCurrentIndex(max(0, combo.findData(item["vrf"]))) open_count = sum(1 for value in settled.values() if not value)
combo.setProperty("previous", combo.currentIndex()) self.settled_network_toggle = self._collapsible(network_layout, self.open_network_table,
for column, text in enumerate((switch["name"], plan["tenant"], item["network"])): self.settled_network_table, open_count,
self.network_table.setItem(row, column, QTableWidgetItem(text)) len(networks) - open_count, "Netze")
self.network_table.setCellWidget(row, 3, combo) missing = sum(1 for entry in networks.values() if not entry["item"]["existing"])
status = QTableWidgetItem() tabs.addTab(network_page, f"Netze ({open_count} zu prüfen, {missing} Prefix(e) fehlen)")
self.network_table.setItem(row, 4, status)
entry = (row, switch, item, combo, status)
self.network_rows.append(entry)
combo.activated.connect(lambda _index, entry=entry: self._vrf_chosen(entry))
self._update_network_row(entry, item["create"])
self._prepare_table(self.network_table, (140, 140, 150, 220, 200))
network_layout.addWidget(self.network_table, 1)
missing = sum(1 for _row, _switch, item, _combo, _status in self.network_rows if not item["existing_vrfs"])
tabs.addTab(network_page, f"Netze ({missing} Prefix(e) fehlen)")
# VLANs ----------------------------------------------------------------- # VLANs -----------------------------------------------------------------
# VLAN decisions apply to all switches of the profile: one row per VID.
self.vlan_rows = [] self.vlan_rows = []
vlans = [(switch, plan, item) for switch, plan in plans for item in plan["vlans"]] merged = {}
if vlans: for switch, plan in plans:
for item in plan["vlans"]:
entry = merged.setdefault(item["vid"], {"item": item, "switches": [], "candidates": {}, "tenants": {}})
entry["switches"].append(switch["name"])
entry["candidates"].update({candidate["id"]: candidate["label"] for candidate in item["candidates"]})
entry["tenants"].update({tenant["id"]: tenant["name"] for tenant in plan["tenants"]})
if merged:
vlan_page = QWidget() vlan_page = QWidget()
vlan_layout = QVBoxLayout(vlan_page) vlan_layout = QVBoxLayout(vlan_page)
vlan_layout.setContentsMargins(0, 12, 0, 0) vlan_layout.setContentsMargins(0, 12, 0, 0)
vlan_layout.addWidget(label( vlan_layout.addWidget(label(
"VLANs der Switch-Ports. Gesucht wird in der Mandantengruppe des Switches über die VLAN-ID; bei " "Gesucht wird in der Mandantengruppe über die VLAN-ID; bei mehreren Treffern entscheiden Mandant, "
"mehreren Treffern entscheiden Mandant, Standort und Name. Zugeordnete VLANs werden an den " "Standort und Name. Neue VLANs erhalten den eingetragenen Namen und Mandanten. Ignorierte VLANs "
"Schnittstellen gesetzt (802.1Q-Modus, untagged/tagged). Neue VLANs erhalten den eingetragenen " "werden weder angelegt noch zugeordnet und fehlen im Label. Die Auswahl gilt für alle Switche "
"Namen und den gewählten Mandanten aus der Mandantengruppe (vorbelegt: Mandant des Switches).", "des Profils und wird gespeichert.", muted=True, wrap=True))
muted=True, wrap=True)) settled = {vid: entry["item"]["stored"] or entry["item"]["method"] in ("vid", "name")
self.vlan_table = QTableWidget(0, 7) for vid, entry in merged.items()}
self.vlan_table.setHorizontalHeaderLabels(["Switch", "VLAN", "Name (Switch)", "NetBox-VLAN", self.open_vlan_table = self._vlan_table()
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"]) self.settled_vlan_table = self._vlan_table()
for switch, plan, item in vlans: for vid in sorted(merged):
row = self.vlan_table.rowCount() self._add_vlan_row(self.settled_vlan_table if settled[vid] else self.open_vlan_table, merged[vid])
self.vlan_table.insertRow(row) for table in (self.open_vlan_table, self.settled_vlan_table):
for column, text in enumerate((switch["name"], str(item["vid"]), item["name"])): self._prepare_table(table, (130, 60, 150, 280, 190, 170, 110))
self.vlan_table.setItem(row, column, QTableWidgetItem(text)) open_count = sum(1 for value in settled.values() if not value)
combo = QComboBox() self.settled_toggle = self._collapsible(vlan_layout, self.open_vlan_table, self.settled_vlan_table,
for candidate in item["candidates"]: open_count, len(merged) - open_count, "VLANs")
combo.addItem(candidate["label"], candidate["id"]) missing = sum(1 for entry in merged.values() if entry["item"]["method"] == "new")
combo.addItem("+ neu anlegen", self.NEW) tabs.addTab(vlan_page, f"VLANs ({open_count} zu prüfen, {missing} fehlen)")
combo.addItem("– nicht zuordnen –", 0)
current = item["netbox_id"] or (0 if item["method"] == "skip" else self.NEW)
combo.setCurrentIndex(max(0, combo.findData(current)))
name = QLineEdit(item["new_name"])
name.setMaxLength(64)
name.setPlaceholderText(item["name"])
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"]))
if item["method"] in ("ambiguous", "new"):
method.setForeground(QColor(theme.color("warning")))
tenant = QComboBox()
for option in plan["tenants"]:
tenant.addItem(option["name"], option["id"])
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
self.vlan_table.setCellWidget(row, 3, combo)
self.vlan_table.setCellWidget(row, 4, name)
self.vlan_table.setCellWidget(row, 5, tenant)
self.vlan_table.setItem(row, 6, method)
def toggle(_index=None, combo=combo, name=name, tenant=tenant):
for widget in (name, tenant):
widget.setEnabled(combo.currentData() == self.NEW)
combo.currentIndexChanged.connect(toggle)
toggle()
self.vlan_rows.append((switch, item, combo, name, tenant))
self._prepare_table(self.vlan_table, (130, 60, 150, 280, 200, 180, 110))
vlan_layout.addWidget(self.vlan_table, 1)
missing = sum(1 for _switch, item, *_widgets in self.vlan_rows if item["method"] == "new")
unclear = sum(1 for _switch, item, *_widgets in self.vlan_rows if item["method"] == "ambiguous")
tabs.addTab(vlan_page, f"VLANs ({missing} fehlen" + (f", {unclear} mehrdeutig)" if unclear else ")"))
self.root.addWidget(tabs, 1) self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner) self.root.addWidget(self.error_banner)
@@ -772,25 +755,129 @@ class SwitchMappingDialog(_Dialog):
for column, width in enumerate(widths): for column, width in enumerate(widths):
table.setColumnWidth(column, width) table.setColumnWidth(column, width)
IGNORE = "\x00ignore"
@staticmethod
def _vlan_table():
table = QTableWidget(0, 7)
table.setHorizontalHeaderLabels(["Switch(e)", "VLAN", "Name (Switch)", "NetBox-VLAN",
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"])
return table
def _add_vlan_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
switches = ", ".join(entry["switches"])
for column, text in enumerate((switches, str(item["vid"]), item["name"])):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
for candidate_id, text in sorted(entry["candidates"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, candidate_id)
combo.addItem("+ neu anlegen", self.NEW)
combo.addItem("– nicht zuordnen –", 0)
combo.addItem("⊘ ignorieren (auf allen Switchen)", self.IGNORE)
current = {"skip": 0, "ignore": self.IGNORE}.get(item["method"], item["netbox_id"] or self.NEW)
combo.setCurrentIndex(max(0, combo.findData(current)))
name = QLineEdit(item["new_name"])
name.setMaxLength(64)
name.setPlaceholderText(item["name"])
tenant = QComboBox()
for tenant_id, text in sorted(entry["tenants"].items(), key=lambda pair: pair[1].casefold()):
tenant.addItem(text, tenant_id)
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"])
+ (" · gespeichert" if item["stored"] else ""))
if not item["stored"] and item["method"] in ("ambiguous", "new"):
method.setForeground(QColor(theme.color("warning")))
table.setCellWidget(row, 3, combo)
table.setCellWidget(row, 4, name)
table.setCellWidget(row, 5, tenant)
table.setItem(row, 6, method)
def toggle(_index=None):
for widget in (name, tenant):
widget.setEnabled(combo.currentData() == self.NEW)
combo.currentIndexChanged.connect(toggle)
toggle()
self.vlan_rows.append((item, combo, name, tenant))
@staticmethod
def _collapsible(layout, open_table, settled_table, open_count, settled_count, noun):
"""Open items on top, decided ones in a collapsed section that can be expanded."""
layout.addWidget(label(f"<b>Zu prüfen ({open_count})</b>" if open_count else
f"Alle {noun} sind zugeordnet oder gespeichert.", wrap=True))
layout.addWidget(open_table, 1)
open_table.setVisible(bool(open_count))
toggle = button("", variant="link")
toggle.setCheckable(True)
def update(expanded):
arrow = "▾" if expanded else "▸"
toggle.setText(f"{arrow} Gespeicherte und eindeutig zugeordnete {noun} ({settled_count})"
+ ("" if expanded else " – zum Bearbeiten ausklappen"))
settled_table.setVisible(expanded and settled_count > 0)
toggle.toggled.connect(update)
update(False)
toggle.setVisible(settled_count > 0)
layout.addWidget(toggle, 0, Qt.AlignLeft)
layout.addWidget(settled_table, 1)
return toggle
@staticmethod
def _network_table():
table = QTableWidget(0, 5)
table.setHorizontalHeaderLabels(["Switch(e)", "Mandant", "Netz", "VRF", "Prefix in NetBox"])
return table
def _add_network_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
texts = (", ".join(entry["switches"]), ", ".join(entry["tenants"]), item["network"])
for column, text in enumerate(texts):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
combo.addItem("Global (keine VRF)", 0)
for vrf_id, text in sorted(entry["vrfs"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, vrf_id)
new_names = list(self._new_vrf_names)
if item["vrf_name"] and item["vrf_name"] not in new_names:
new_names.append(item["vrf_name"])
for name in new_names:
combo.addItem(f"{name} (neu)", f"new:{name}")
combo.addItem("+ Neue VRF …", self.NEW)
current = f"new:{item['vrf_name']}" if item["vrf_name"] else item["vrf_id"]
combo.setCurrentIndex(max(0, combo.findData(current)))
combo.setProperty("previous", combo.currentIndex())
table.setCellWidget(row, 3, combo)
status = QTableWidgetItem()
table.setItem(row, 4, status)
row_entry = (item, combo, status)
self.network_rows.append(row_entry)
combo.activated.connect(lambda _index, row_entry=row_entry: self._vrf_chosen(row_entry))
self._update_network_row(row_entry, item["create"])
def _vrf_chosen(self, entry): def _vrf_chosen(self, entry):
_row, switch, _item, combo, _status = entry _item, combo, _status = entry
if combo.currentData() == self.NEW: if combo.currentData() == self.NEW:
name = ask_text(self, "Neue VRF", "Name der neuen VRF. Sie wird beim Übertragen mit dem Mandanten " name = ask_text(self, "Neue VRF", "Name der neuen VRF. Sie wird beim Übertragen mit dem Mandanten "
"des Switches angelegt.") "des Switches angelegt.")
if not name: if not name:
combo.setCurrentIndex(combo.property("previous")) combo.setCurrentIndex(combo.property("previous"))
return return
# Offer the new VRF in every row of the same switch. self._new_vrf_names.append(name)
for _r, other_switch, _i, other, _s in self.network_rows: # Offer the new VRF in every network row.
if other_switch["id"] == switch["id"] and other.findData(name) < 0: for _other_item, other, _other_status in self.network_rows:
other.insertItem(other.count() - 1, name, name) if other.findData(f"new:{name}") < 0:
combo.setCurrentIndex(combo.findData(name)) other.insertItem(other.count() - 1, f"{name} (neu)", f"new:{name}")
combo.setCurrentIndex(combo.findData(f"new:{name}"))
combo.setProperty("previous", combo.currentIndex()) combo.setProperty("previous", combo.currentIndex())
self._update_network_row(entry) self._update_network_row(entry)
def _update_network_row(self, entry, create=None): def _update_network_row(self, entry, create=None):
_row, _switch, item, combo, status = entry item, combo, status = entry
if combo.currentData() in item["existing_vrfs"]: if combo.currentData() in item["existing"]:
status.setText("vorhanden") status.setText("vorhanden")
status.setFlags(Qt.ItemIsEnabled) status.setFlags(Qt.ItemIsEnabled)
status.setData(Qt.CheckStateRole, None) status.setData(Qt.CheckStateRole, None)
@@ -834,25 +921,32 @@ class SwitchMappingDialog(_Dialog):
stored.pop(neighbor["local_port"], None) stored.pop(neighbor["local_port"], None)
else: else:
stored[neighbor["local_port"]] = chosen stored[neighbor["local_port"]] = chosen
for switch, plan in self.plans: network_map = dict(self.previous_network_map)
result[switch["id"]].update({"network_vrfs": {}, "create_prefixes": [], "create_vlans": [], "vlan_map": {}}) for item, combo, status in self.network_rows:
for _row, switch, item, combo, status in self.network_rows: chosen = combo.currentData()
choices = result[switch["id"]] new_name = chosen[4:] if isinstance(chosen, str) and chosen.startswith("new:") else ""
choices["network_vrfs"][item["network"]] = combo.currentData() network_map[item["network"]] = {
if status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked: "vrf_id": chosen if isinstance(chosen, int) and chosen else None,
choices["create_prefixes"].append(item["network"]) "vrf_name": new_name,
for switch, item, combo, name, tenant in self.vlan_rows: "create": status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked,
}
self.network_map = network_map
vlan_map = dict(self.previous_vlan_map)
for item, combo, name, tenant in self.vlan_rows:
chosen = combo.currentData() chosen = combo.currentData()
if chosen == self.NEW: if chosen == self.NEW:
if not name.text().strip(): if not name.text().strip():
self.show_error(f"{switch['name']}: Bitte einen Namen für das neue VLAN {item['vid']} eingeben.") self.show_error(f"Bitte einen Namen für das neue VLAN {item['vid']} eingeben.")
return return
choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()} choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()}
elif chosen == self.IGNORE:
choice = {"action": "ignore"}
elif chosen: elif chosen:
choice = {"action": "map", "id": chosen} choice = {"action": "map", "id": chosen}
else: else:
choice = {"action": "skip"} choice = {"action": "skip"}
result[switch["id"]]["vlan_map"][str(item["vid"])] = choice vlan_map[str(item["vid"])] = choice
self.vlan_map = vlan_map
self.result = result self.result = result
super().accept() super().accept()
+2
View File
@@ -35,6 +35,7 @@ from netbox_sync.ui.resources import resource_path
from netbox_sync.ui.state import AppState from netbox_sync.ui.state import AppState
from netbox_sync.ui.tasks import TaskManager, log_bus from netbox_sync.ui.tasks import TaskManager, log_bus
from netbox_sync.ui.theme import theme from netbox_sync.ui.theme import theme
from netbox_sync.ui.updates import UpdateManager
from netbox_sync.ui.widgets import Badge, Toast, button, label from netbox_sync.ui.widgets import Badge, Toast, button, label
NAVIGATION = ( NAVIGATION = (
@@ -81,6 +82,7 @@ class MainWindow(QMainWindow):
self.state = AppState() self.state = AppState()
self.tasks = TaskManager() self.tasks = TaskManager()
self.actions = Actions(self) self.actions = Actions(self)
self.updates = UpdateManager(self)
self.pages = {} self.pages = {}
self.nav_buttons = {} self.nav_buttons = {}
self.unseen_errors = 0 self.unseen_errors = 0
+17 -2
View File
@@ -81,6 +81,18 @@ class SettingsPage(Page):
"nicht auf einem anderen Rechner entschlüsselt werden.", muted=True, wrap=True)) "nicht auf einem anderen Rechner entschlüsselt werden.", muted=True, wrap=True))
self.body.addWidget(data) self.body.addWidget(data)
updates = Card("Updates", "Neue Versionen kommen aus den Releases von Netbox-Import-Desktop (Gitea).")
line = QHBoxLayout()
self.auto_update = checkbox("Beim Start nach Updates suchen")
line.addWidget(self.auto_update)
line.addStretch(1)
line.addWidget(button("Jetzt nach Updates suchen", "refresh", on_click=lambda: window.updates.check()))
updates.add(line)
updates.add(label("Vor der Installation wird immer gefragt. Die installierte Version aktualisiert sich über "
"das Setup, die portable EXE tauscht sich selbst aus; danach startet die Anwendung neu.",
muted=True, wrap=True))
self.body.addWidget(updates)
about = Card("Über") about = Card("Über")
about.add(label(f"<b>{APP_NAME}</b> Version {APP_VERSION}")) about.add(label(f"<b>{APP_NAME}</b> Version {APP_VERSION}"))
about.add(label(f"© {APP_PUBLISHER}", muted=True)) about.add(label(f"© {APP_PUBLISHER}", muted=True))
@@ -90,18 +102,21 @@ class SettingsPage(Page):
self.parallel.valueChanged.connect(lambda value: self.state.update_settings(parallel_ssh=value)) self.parallel.valueChanged.connect(lambda value: self.state.update_settings(parallel_ssh=value))
self.enable_lldp.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value)) self.enable_lldp.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value))
self.parallel_wmi.valueChanged.connect(lambda value: self.state.update_settings(parallel_wmi=value)) self.parallel_wmi.valueChanged.connect(lambda value: self.state.update_settings(parallel_wmi=value))
self.auto_update.toggled.connect(lambda value: self.state.update_settings(auto_update_check=value))
self.state.settings_changed.connect(self.load) self.state.settings_changed.connect(self.load)
self.load() self.load()
def load(self): def load(self):
settings = self.state.settings settings = self.state.settings
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()): widgets_ = (self.parallel, self.parallel_wmi, self.enable_lldp, self.auto_update, *self.theme_buttons.values())
for widget in widgets_:
widget.blockSignals(True) widget.blockSignals(True)
self.parallel.setValue(int(settings.get("parallel_ssh", 4))) self.parallel.setValue(int(settings.get("parallel_ssh", 4)))
self.parallel_wmi.setValue(int(settings.get("parallel_wmi", 8))) self.parallel_wmi.setValue(int(settings.get("parallel_wmi", 8)))
self.enable_lldp.setChecked(bool(settings.get("enable_lldp"))) self.enable_lldp.setChecked(bool(settings.get("enable_lldp")))
self.auto_update.setChecked(bool(settings.get("auto_update_check", True)))
self.theme_buttons.get(settings.get("theme", "system"), self.theme_buttons["system"]).setChecked(True) self.theme_buttons.get(settings.get("theme", "system"), self.theme_buttons["system"]).setChecked(True)
for widget in (self.parallel, self.parallel_wmi, self.enable_lldp, *self.theme_buttons.values()): for widget in widgets_:
widget.blockSignals(False) widget.blockSignals(False)
def _set_theme(self, mode): def _set_theme(self, mode):
+3 -2
View File
@@ -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, vlan_label from netbox_sync.core.switches import PLATFORMS, ignored_vlans, vlan_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
@@ -108,7 +108,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(row.get("vlans"))), Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans(
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
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", "")),
+106
View File
@@ -0,0 +1,106 @@
"""Update check on start and on demand, download and installation."""
import tempfile
import webbrowser
from pathlib import Path
from PySide6.QtCore import QObject, QThreadPool, QTimer
from netbox_sync import APP_VERSION
from netbox_sync.core import updater
from netbox_sync.ui import widgets
from netbox_sync.ui.tasks import Task, logger
class UpdateManager(QObject):
def __init__(self, window):
super().__init__(window)
self.window = window
self.state = window.state
self.tasks = window.tasks
self._check = None
def check_on_start(self):
updater.remove_leftovers()
if self.state.settings.get("auto_update_check", True):
# A moment after start, so the window is usable right away.
QTimer.singleShot(4000, lambda: self.check(silent=True))
def check(self, silent=False):
"""Ask Gitea for a newer release without blocking other tasks."""
if self._check is not None:
return
task = Task(lambda _ctx: updater.check_for_update(), "app", "Nach Updates suchen")
self._check = task
def done(release):
if release is None:
logger("app").info("Keine neuere Version gefunden (installiert: %s)", APP_VERSION)
if not silent:
self.window.toast(f"{APP_VERSION} ist die aktuelle Version.", "info")
return
if silent and self.state.settings.get("skipped_version") == release["version"]:
return
self._offer(release)
def failed(error):
logger("app").warning("Update-Prüfung fehlgeschlagen: %s", error)
if not silent:
widgets.message(self.window, "Update-Prüfung fehlgeschlagen", str(error), "warning")
task.signals.succeeded.connect(done)
task.signals.failed.connect(failed)
task.signals.finished.connect(lambda: setattr(self, "_check", None))
QThreadPool.globalInstance().start(task)
def _offer(self, release):
kind = updater.install_kind()
asset = updater.pick_asset(release, kind) if kind else None
text = (f"Version {release['version']} ist verfügbar (installiert: {APP_VERSION}).\n\n"
+ ("Das Update wird heruntergeladen und installiert; die Anwendung startet danach neu."
if asset else "Für diese Installation gibt es keine passende Datei – bitte die Release-Seite "
"öffnen."))
buttons = ("Später", "Diese Version überspringen", "Jetzt aktualisieren" if asset else "Release-Seite öffnen")
choice = widgets.message(self.window, "Update verfügbar", text, "info", release["notes"] or None,
buttons=buttons, default=2)
if choice == 1:
self.state.update_settings(skipped_version=release["version"])
elif choice == 2 and asset:
self._install(release, kind, *asset)
elif choice == 2 and release["page"]:
webbrowser.open(release["page"])
def _install(self, release, kind, name, asset):
if self.tasks.busy:
widgets.message(self.window, "Bitte warten", f"„{self.tasks.current.title}“ läuft noch. Das Update "
"kann danach über Einstellungen › Updates gestartet werden.", "info")
return
if kind == "portable":
target = updater.portable_download_path()
else:
target = Path(tempfile.mkdtemp(prefix="netbox-sync-update-")) / name
def work(ctx):
ctx.log(f"Lade {name} ({release['version']}) herunter …")
def progress(done, total):
ctx.progress(done // 1024, max(total // 1024, 1), f"{done / 1_048_576:.1f} MB")
return updater.download(asset, target, progress, lambda: ctx.cancelled)
def downloaded(path):
try:
if kind == "portable":
updater.apply_portable(path)
else:
updater.apply_installer(path)
except OSError as error:
widgets.error(self.window, "Update fehlgeschlagen", f"Das Update konnte nicht gestartet werden: "
f"{error}")
return
logger("app").log(25, "Update auf %s wird installiert – Anwendung wird beendet", release["version"])
# After the task has finished, so closing does not ask about a running task.
QTimer.singleShot(0, self.window.close)
self.tasks.run(work, title=f"Update {release['version']} herunterladen", area="app",
on_success=downloaded,
on_error=lambda error: widgets.error(self.window, "Update fehlgeschlagen", str(error)))
+70 -3
View File
@@ -136,7 +136,8 @@ def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
plan = plan_switch_sync(nb, switch, snapshot) plan = plan_switch_sync(nb, switch, snapshot)
assert [(item["vid"], item["netbox_id"], item["method"], item["new_name"]) for item in plan["vlans"]] == [ assert [(item["vid"], item["netbox_id"], item["method"], item["new_name"]) for item in plan["vlans"]] == [
(1, None, "new", "VLAN1"), (10, 110, "vid", "VLAN10"), (20, None, "new", "Clients")] (1, None, "new", "VLAN1"), (10, 110, "vid", "VLAN10"), (20, None, "new", "Clients")]
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf": "", "existing_vrfs": [], "create": True}] assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf_id": 0, "vrf_name": "", "existing": [],
"create": True, "stored": False}]
# Not approved: nothing is created, only the existing VLAN 10 is assigned. # Not approved: nothing is created, only the existing VLAN 10 is assigned.
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True) report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
@@ -146,8 +147,7 @@ def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access" assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access"
assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None
switch.update({"vlan_map": {"20": {"action": "new", "name": "Clients"}}, "create_prefixes": ["10.1.0.0/24"], switch.update({"vlan_map": {"20": {"action": "new", "name": "Clients"}}, "network_map": {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "Kunde-Mgmt", "create": True}}})
"network_vrfs": {"10.1.0.0/24": "Kunde-Mgmt"}})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False) report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == [] assert report["errors"] == []
assert nb.ipam.vrfs.created == [{"name": "Kunde-Mgmt", "tenant": 7}] assert nb.ipam.vrfs.created == [{"name": "Kunde-Mgmt", "tenant": 7}]
@@ -213,3 +213,70 @@ def test_new_vlan_can_get_another_tenant_of_the_group():
nb.ipam.vlans.records[-1].tenant_group = group nb.ipam.vlans.records[-1].tenant_group = group
again = plan_switch_sync(nb, switch, snapshot)["vlans"][0] again = plan_switch_sync(nb, switch, snapshot)["vlans"][0]
assert (again["netbox_id"], again["method"]) == (nb.ipam.vlans.records[-1].id, "manual"), "never created twice" assert (again["netbox_id"], again["method"]) == (nb.ipam.vlans.records[-1].id, "manual"), "never created twice"
def test_ignored_vlans_are_left_out_everywhere():
nb, switch, snapshot = _numbered_setup()
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
snapshot["interfaces"][0]["vlans"] = {"untagged": [10], "tagged": [20, 30], "tagged_all": False}
switch["vlan_map"] = {"20": {"action": "ignore"}, "30": {"action": "new", "name": "Drucker"}}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[20]["method"], by_vid[20]["stored"]) == ("ignore", True)
assert by_vid[10]["stored"] is False
assert {item["name"]: item["vlan_label"] for item in plan["interfaces"]}["1/1/1"] == "10,30"
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert [payload["vid"] for payload in nb.ipam.vlans.created] == [30]
port = nb.dcim.interfaces.get(1)
assert port.label == "10,30" and port.tagged_vlans == [nb.ipam.vlans.records[-1].id]
def test_vlan_decisions_move_from_switches_to_the_profile(tmp_path):
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
profile = {"name": "Kunde", "switches": [{"id": "s", "name": "sw", "password": "x",
"vlan_map": {"5": {"action": "ignore"}}, "create_vlans": [6]}]}
store.save({"Kunde": profile}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["vlan_map"] == {"5": {"action": "ignore"}}
assert "vlan_map" not in loaded["switches"][0] and "create_vlans" not in loaded["switches"][0]
def test_vrfs_of_the_tenant_group_are_offered_and_found():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
rz = SimpleNamespace(id=8, name="RZ")
nb.ipam.vrfs.records += [
Record(nb.ipam.vrfs, id=60, name="Mgmt", tenant=rz, tenant_group=group),
Record(nb.ipam.vrfs, id=61, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
]
nb.ipam.prefixes.records.append(Record(nb.ipam.prefixes, id=70, prefix="10.10.167.0/24", vrf=SimpleNamespace(id=60)))
snapshot["interfaces"][0]["ip_addresses"] = ["10.10.167.5/24"]
plan = plan_switch_sync(nb, switch, snapshot)
assert plan["vrfs"] == [{"id": 60, "label": "Mgmt (RZ)"}], "group VRFs only"
assert plan["networks"][0] == {"network": "10.10.167.0/24", "vrf_id": 60, "vrf_name": "", "existing": [60],
"create": True, "stored": False}
switch["network_map"] = {"10.10.167.0/24": {"vrf_id": 60, "vrf_name": "", "create": False}}
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == [] and report["prefixes_created"] == 0 and nb.ipam.vrfs.created == []
assert nb.ipam.ip_addresses.created[0]["vrf"] == 60
assert plan_switch_sync(nb, switch, snapshot)["networks"][0]["stored"] is True
def test_legacy_network_choices_still_work_and_migrate(tmp_path):
nb, switch, snapshot = _numbered_setup()
snapshot["interfaces"][0]["ip_addresses"] = ["10.1.0.1/24"]
switch.update({"network_vrfs": {"10.1.0.0/24": ""}, "create_prefixes": ["10.1.0.0/24"]})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
assert report["prefixes_created"] == 1
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
store.save({"Kunde": {"name": "Kunde", "switches": [dict(switch, password="x")]}}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["network_map"] == {"10.1.0.0/24": {"vrf_id": None, "vrf_name": "", "create": True}}
assert "network_vrfs" not in loaded["switches"][0]
+75
View File
@@ -0,0 +1,75 @@
import sys
import pytest
from netbox_sync.core import updater
RELEASE = {
"tag_name": "v4.7.0", "name": "Netbox-Import-Desktop v4.7.0", "body": "- neu", "draft": False,
"prerelease": False, "html_url": "https://example.invalid/releases/tag/v4.7.0",
"assets": [
{"name": "NetBox VM Import.exe", "size": 4, "browser_download_url": "https://example.invalid/portable"},
{"name": "NetBoxSynchronizer-Setup-4.7.0.exe", "size": 4, "browser_download_url": "https://example.invalid/setup"},
],
}
class _Response:
def __init__(self, payload=None, chunks=(), length=None):
self.payload, self.chunks = payload, chunks
self.headers = {"Content-Length": str(length)} if length else {}
def raise_for_status(self):
return None
def json(self):
return self.payload
def iter_content(self, _size):
return iter(self.chunks)
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def test_versions_are_compared_numerically():
assert updater.parse_version("v4.10.0") > updater.parse_version("4.9.3")
assert updater.parse_version("v5") == (5, 0, 0)
def test_newer_release_is_offered_with_matching_assets(monkeypatch):
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(RELEASE))
release = updater.check_for_update("4.6.0")
assert release["version"] == "4.7.0" and release["notes"] == "- neu"
assert updater.pick_asset(release, "portable")[0] == "NetBox VM Import.exe"
assert updater.pick_asset(release, "installer")[0] == "NetBoxSynchronizer-Setup-4.7.0.exe"
assert updater.check_for_update("4.7.0") is None
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(dict(RELEASE, prerelease=True)))
assert updater.check_for_update("4.6.0") is None
def test_incomplete_download_is_discarded(monkeypatch, tmp_path):
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab"]))
with pytest.raises(updater.UpdateError):
updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
assert list(tmp_path.iterdir()) == []
monkeypatch.setattr(updater.requests, "get", lambda *_a, **_k: _Response(chunks=[b"ab", b"cd"]))
target = updater.download({"url": "x", "size": 4}, tmp_path / "setup.exe")
assert target.read_bytes() == b"abcd"
def test_portable_exe_is_swapped_and_restarted(monkeypatch, tmp_path):
exe = tmp_path / "NetBox VM Import.exe"
exe.write_bytes(b"old")
new = tmp_path / "NetBox VM Import.new.exe"
new.write_bytes(b"new")
started = []
monkeypatch.setattr(sys, "executable", str(exe))
monkeypatch.setattr(updater.subprocess, "Popen", lambda args, **_kwargs: started.append(args))
updater.apply_portable(new)
assert exe.read_bytes() == b"new" and not new.exists()
assert (tmp_path / "NetBox VM Import.old.exe").read_bytes() == b"old"
assert started == [[str(exe)]]