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]>
This commit is contained in:
1 parent
3db5e83f0a
commit
e499d854a9
13 files changed
+600
-101
No files matched your search
@@ -21,6 +21,8 @@ DEFAULT_SETTINGS = {
|
||||
"create_cables": True,
|
||||
"offline_mode": False, # collect and export to JSON without NetBox
|
||||
"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__)
|
||||
@@ -118,6 +120,8 @@ def empty_profile(name):
|
||||
"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.
|
||||
"clients": dict(DEFAULT_CLIENT_OPTIONS),
|
||||
}
|
||||
@@ -167,6 +171,7 @@ class ProfileStore:
|
||||
"cluster_map": dict(record.get("cluster_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()
|
||||
if key in DEFAULT_CLIENT_OPTIONS}},
|
||||
})
|
||||
@@ -174,11 +179,15 @@ class ProfileStore:
|
||||
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
|
||||
for switch in record.get("switches", []):
|
||||
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
|
||||
# Migration from 4.5: VLAN decisions were stored per 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.
|
||||
if not profile["sources"] and record.get("esxi_host"):
|
||||
@@ -237,6 +246,7 @@ class ProfileStore:
|
||||
"cluster_map": dict(profile.get("cluster_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)),
|
||||
})
|
||||
|
||||
|
||||
@@ -1210,24 +1210,24 @@ def plan_switch_sync(nb, config, snapshot):
|
||||
neighbors.append(dict(neighbor, device_id=device_id, method=method))
|
||||
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)}
|
||||
vrfs = sorted(tenant_vrfs.values(), key=str.casefold)
|
||||
stored_vrfs = config.get("network_vrfs") or {}
|
||||
create_prefixes = config.get("create_prefixes")
|
||||
vrf_records = candidate_vrfs(nb, tenant_id)
|
||||
vrfs = [{"id": vrf.id, "label": vrf_choice_label(vrf)}
|
||||
for vrf in sorted(vrf_records, key=lambda item: (item.name or "").casefold())]
|
||||
networks = []
|
||||
for network in snapshot_networks(snapshot):
|
||||
# Where the prefix already exists: "" = global, otherwise a tenant VRF.
|
||||
existing = set()
|
||||
for prefix in nb.ipam.prefixes.filter(prefix=network):
|
||||
vrf_id = related_id(prefix, "vrf")
|
||||
if vrf_id is None or vrf_id in tenant_vrfs:
|
||||
existing.add(tenant_vrfs.get(vrf_id, ""))
|
||||
existing = sorted(existing)
|
||||
vrf = stored_vrfs[network] if network in stored_vrfs else (existing[0] if existing else "")
|
||||
if vrf and vrf not in vrfs:
|
||||
vrfs.append(vrf) # chosen earlier as new VRF, not created yet
|
||||
networks.append({"network": network, "vrf": vrf, "existing_vrfs": existing,
|
||||
"create": create_prefixes is None or network in create_prefixes})
|
||||
# Where the prefix already exists: 0 = global, otherwise a VRF of the tenant group.
|
||||
existing = sorted({related_id(prefix, "vrf") or 0 for prefix in nb.ipam.prefixes.filter(prefix=network)}
|
||||
& ({0} | {vrf.id for vrf in vrf_records}), key=lambda value: (value == 0, value))
|
||||
choice = _network_choice(config, network)
|
||||
if choice is not None:
|
||||
vrf_id = _resolve_vrf_choice(choice, vrf_records, tenant_id)
|
||||
vrf_id = vrf_id if isinstance(vrf_id, int) else 0
|
||||
networks.append({"network": network, "vrf_id": vrf_id,
|
||||
"vrf_name": choice.get("vrf_name") if not vrf_id else "",
|
||||
"existing": existing, "create": bool(choice.get("create")), "stored": True})
|
||||
else:
|
||||
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()}
|
||||
candidates, vlan_matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, related_id(device, "site"))
|
||||
@@ -1321,33 +1321,80 @@ class _RemoteLookup:
|
||||
_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):
|
||||
"""``{network: VRF ID or None}``; VRFs chosen by name are created for the tenant."""
|
||||
by_name = {vrf.name: vrf.id for vrf in nb.ipam.vrfs.filter(tenant_id=tenant_id)}
|
||||
chosen = config.get("network_vrfs") or {}
|
||||
"""``{network: VRF ID or None}``; new VRFs are created for the switch's tenant."""
|
||||
vrf_records = candidate_vrfs(nb, tenant_id)
|
||||
created = {}
|
||||
result = {}
|
||||
for network in snapshot_networks(snapshot):
|
||||
name = chosen.get(network) or ""
|
||||
if name and name not in by_name:
|
||||
report["vrfs_created"] += 1
|
||||
report["changes"].append(f"VRF {name} neu")
|
||||
by_name[name] = _NEW if dry_run else nb.ipam.vrfs.create({"name": name, "tenant": tenant_id}).id
|
||||
result[network] = by_name[name] if name else None
|
||||
choice = _network_choice(config, network) or {}
|
||||
resolved = _resolve_vrf_choice(choice, vrf_records, tenant_id)
|
||||
if isinstance(resolved, str):
|
||||
if resolved not in created:
|
||||
report["vrfs_created"] += 1
|
||||
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
|
||||
|
||||
|
||||
def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
|
||||
"""Create missing prefixes that were approved; existing ones stay untouched."""
|
||||
approved = set(config.get("create_prefixes") or [])
|
||||
for network in snapshot_networks(snapshot):
|
||||
vrf_id = vrf_ids.get(network)
|
||||
if network not in approved:
|
||||
if not (_network_choice(config, network) or {}).get("create"):
|
||||
continue
|
||||
if vrf_id != _NEW and list(nb.ipam.prefixes.filter(prefix=network, vrf_id=vrf_id or "null")):
|
||||
continue
|
||||
try:
|
||||
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})")
|
||||
if not dry_run:
|
||||
nb.ipam.prefixes.create({"prefix": network, "status": "active", "tenant": tenant_id, "vrf": vrf_id})
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user