feat: offline mode with JSON export/import
Collect VMs and switch data without NetBox, export them to a credential-free .nbsync.json file and import it later where NetBox is reachable. Toggled by a global sidebar checkbox. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
c3b5fb547e
commit
52f1e4b5f1
14 files changed
+437
-33
No files matched your search
@@ -49,6 +49,14 @@ Bestehende Kundenprofile der Vorgängerversion („NetBox VM Import“) werden a
|
||||
- Kabel aus LLDP/CDP auch bei FQDN-Systemnamen oder über die Management-IP
|
||||
- Die Switch-Konfiguration wird nur verändert, wenn „LLDP bei Bedarf aktivieren“ ausdrücklich eingeschaltet ist
|
||||
|
||||
**Offline-Modus (ohne NetBox)**
|
||||
- Checkbox „Offline-Modus (ohne NetBox)“ in der Seitenleiste – gilt global, unabhängig vom Kundenprofil
|
||||
- VMs und Switche werden ohne NetBox-Verbindung ausgelesen; Switche lassen sich dann manuell per Name anlegen
|
||||
- Ausgewählte VMs bzw. ausgelesene Switche werden als JSON-Datei (`*.nbsync.json`) exportiert – ohne Passwörter,
|
||||
Tokens oder Benutzernamen
|
||||
- Auf einem Rechner mit NetBox-Zugang lädt „Aus Datei laden …“ (Seiten VMs und Switche) die Datei; danach laufen
|
||||
Import-Assistent bzw. Dry-Run-Vorschau wie gewohnt. Switche werden über NetBox-Geräte-ID oder Namen zugeordnet
|
||||
|
||||
**VRFs & Netze**
|
||||
- Mehrere VRFs oder Präfixe für einen Mandanten gesammelt anlegen
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ DEFAULT_SETTINGS = {
|
||||
"parallel_ssh": 4, # concurrent switch discoveries
|
||||
"enable_lldp": False, # allow configuration changes on switches
|
||||
"create_cables": True,
|
||||
"offline_mode": False, # collect and export to JSON without NetBox
|
||||
}
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""JSON exchange files for working without a NetBox connection.
|
||||
|
||||
VMs and switch discovery results are collected where the hypervisors and
|
||||
switches are reachable, exported to a file and imported later on a machine
|
||||
that can reach NetBox. Credentials are never written to the file.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from netbox_sync import APP_VERSION
|
||||
|
||||
FORMAT = "netbox-sync-export"
|
||||
FORMAT_VERSION = 1
|
||||
FILE_SUFFIX = ".nbsync.json"
|
||||
|
||||
# Switch fields that describe the device; everything else (credentials) stays local.
|
||||
SWITCH_FIELDS = ("id", "name", "device_id", "platform", "host", "port")
|
||||
VM_RUNTIME_FIELDS = ("id", "source_id")
|
||||
|
||||
|
||||
class ExchangeError(ValueError):
|
||||
"""The file is not a valid exchange file."""
|
||||
|
||||
|
||||
def build_export(vms=(), switches=(), profile_name=""):
|
||||
"""``switches`` is an iterable of ``(switch config, snapshot)`` pairs."""
|
||||
return {
|
||||
"format": FORMAT,
|
||||
"version": FORMAT_VERSION,
|
||||
"created": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
||||
"tool_version": APP_VERSION,
|
||||
"profile": profile_name,
|
||||
"vms": [{key: value for key, value in vm.items() if key not in VM_RUNTIME_FIELDS} for vm in vms],
|
||||
"switches": [
|
||||
{"switch": {key: switch[key] for key in SWITCH_FIELDS if key in switch}, "snapshot": snapshot}
|
||||
for switch, snapshot in switches
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def write_export(path, data):
|
||||
path = Path(path)
|
||||
temp_path = path.with_name(path.name + ".tmp")
|
||||
with temp_path.open("w", encoding="utf-8") as stream:
|
||||
json.dump(data, stream, indent=2, ensure_ascii=False)
|
||||
temp_path.replace(path)
|
||||
|
||||
|
||||
def read_export(path):
|
||||
try:
|
||||
with Path(path).open("r", encoding="utf-8") as stream:
|
||||
data = json.load(stream)
|
||||
except json.JSONDecodeError as error:
|
||||
raise ExchangeError(f"Keine gültige JSON-Datei: {error}") from error
|
||||
return validate(data)
|
||||
|
||||
|
||||
def validate(data):
|
||||
if not isinstance(data, dict) or data.get("format") != FORMAT:
|
||||
raise ExchangeError("Die Datei ist keine Exportdatei des NetBox Synchronizers.")
|
||||
version = data.get("version")
|
||||
if not isinstance(version, int) or version > FORMAT_VERSION:
|
||||
raise ExchangeError(f"Exportformat Version {version} wird von dieser Programmversion nicht unterstützt. "
|
||||
"Bitte den NetBox Synchronizer aktualisieren.")
|
||||
vms = data.get("vms") or []
|
||||
switches = data.get("switches") or []
|
||||
if not isinstance(vms, list) or not isinstance(switches, list):
|
||||
raise ExchangeError("Die Datei ist beschädigt (Listen erwartet).")
|
||||
for vm in vms:
|
||||
if not isinstance(vm, dict) or not vm.get("name") or not vm.get("source"):
|
||||
raise ExchangeError("Die Datei enthält eine VM ohne Name oder Quelle.")
|
||||
vm.setdefault("interfaces", [])
|
||||
vm.setdefault("cluster", "")
|
||||
vm.setdefault("status", "offline")
|
||||
for key in ("vcpus", "memory", "disk"):
|
||||
vm[key] = int(vm.get(key) or 0)
|
||||
for item in switches:
|
||||
switch = item.get("switch") if isinstance(item, dict) else None
|
||||
snapshot = item.get("snapshot") if isinstance(item, dict) else None
|
||||
if not isinstance(switch, dict) or not switch.get("name") or not isinstance(snapshot, dict) \
|
||||
or not isinstance(snapshot.get("interfaces"), list):
|
||||
raise ExchangeError("Die Datei enthält einen Switch ohne Name oder Ausleseergebnis.")
|
||||
return data
|
||||
|
||||
|
||||
def prepare_vms(vms, prefix="file"):
|
||||
"""Give imported VMs the runtime IDs the UI expects (``id``, ``source_id``)."""
|
||||
result = []
|
||||
for index, vm in enumerate(vms):
|
||||
item = dict(vm)
|
||||
item["source_id"] = f"{prefix}:{item['source']}"
|
||||
item["id"] = f"{item['source_id']}:{index}:{item['name']}"
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def merge_switches(profile_switches, items, new_id):
|
||||
"""Match imported switches to profile entries by NetBox device ID or name.
|
||||
|
||||
Unknown switches are appended without credentials. Returns
|
||||
``(snapshots by profile switch id, number of switches added)``.
|
||||
"""
|
||||
by_device = {switch.get("device_id"): switch for switch in profile_switches if switch.get("device_id")}
|
||||
by_name = {switch.get("name", "").casefold(): switch for switch in profile_switches}
|
||||
snapshots, added = {}, 0
|
||||
for item in items:
|
||||
imported = item["switch"]
|
||||
target = by_device.get(imported.get("device_id")) if imported.get("device_id") else None
|
||||
target = target or by_name.get(imported["name"].casefold())
|
||||
if target is None:
|
||||
target = {
|
||||
"id": new_id(),
|
||||
"name": imported["name"],
|
||||
"device_id": imported.get("device_id"),
|
||||
"platform": imported.get("platform", "auto"),
|
||||
"host": imported.get("host", ""),
|
||||
"port": int(imported.get("port", 22)),
|
||||
"username": "",
|
||||
"password": "",
|
||||
"enabled": False,
|
||||
}
|
||||
profile_switches.append(target)
|
||||
by_name[target["name"].casefold()] = target
|
||||
added += 1
|
||||
snapshots[target["id"]] = item["snapshot"]
|
||||
return snapshots, added
|
||||
@@ -772,11 +772,21 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
device-type templates and manual corrections in NetBox are preserved.
|
||||
"""
|
||||
report = _new_report()
|
||||
device_id = int(config["device_id"])
|
||||
device = nb.dcim.devices.get(device_id)
|
||||
if not device:
|
||||
report["errors"].append(f"NetBox-Gerät #{device_id} existiert nicht mehr")
|
||||
return report
|
||||
if config.get("device_id"):
|
||||
device_id = int(config["device_id"])
|
||||
device = nb.dcim.devices.get(device_id)
|
||||
if not device:
|
||||
report["errors"].append(f"NetBox-Gerät #{device_id} existiert nicht mehr")
|
||||
return report
|
||||
else:
|
||||
# Switches captured in offline mode are only known by name.
|
||||
matches = list(nb.dcim.devices.filter(name=config["name"]))
|
||||
if len(matches) != 1:
|
||||
report["errors"].append(f"NetBox-Gerät „{config['name']}“ " +
|
||||
("nicht gefunden" if not matches else "ist nicht eindeutig"))
|
||||
return report
|
||||
device = matches[0]
|
||||
device_id = device.id
|
||||
tenant_id = related_id(device, "tenant")
|
||||
existing = _device_interfaces(nb, device_id)
|
||||
records = {}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""Long-running operations started from the UI. Everything here runs in background tasks."""
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
|
||||
from netbox_sync.core import netbox
|
||||
from netbox_sync.core import exchange, netbox
|
||||
from netbox_sync.core.config import known_hosts_path
|
||||
from netbox_sync.core.netbox import NetBoxError, related_name
|
||||
from netbox_sync.core.switches import (
|
||||
@@ -144,7 +146,8 @@ class Actions:
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_vms(self):
|
||||
if not self.require_netbox_config():
|
||||
offline = self.state.offline
|
||||
if not offline and not self.require_netbox_config():
|
||||
return
|
||||
sources = [dict(source) for source in self.state.sources if source.get("enabled", True)]
|
||||
if not sources:
|
||||
@@ -154,13 +157,15 @@ class Actions:
|
||||
self.window.navigate("connections")
|
||||
self.window.pages["connections"].add_source()
|
||||
return
|
||||
connect = self._connector()
|
||||
connect = None if offline else self._connector()
|
||||
|
||||
def work(ctx):
|
||||
nb = connect(ctx)
|
||||
engine = VMSyncEngine(nb, log=area_log("vm"))
|
||||
engine.load_targets()
|
||||
ctx.check_cancelled()
|
||||
nb = engine = None
|
||||
if connect is not None:
|
||||
nb = connect(ctx)
|
||||
engine = VMSyncEngine(nb, log=area_log("vm"))
|
||||
engine.load_targets()
|
||||
ctx.check_cancelled()
|
||||
vms, failures = [], []
|
||||
ctx.progress(0, len(sources), "Lese Quellen …")
|
||||
with ThreadPoolExecutor(max_workers=min(4, len(sources))) as pool:
|
||||
@@ -183,7 +188,8 @@ class Actions:
|
||||
|
||||
def success(result):
|
||||
nb, engine, vms, failures = result
|
||||
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}", engine)
|
||||
if nb is not None:
|
||||
self.state.set_netbox(nb, "ok", f"Verbunden · NetBox {nb.netbox_version}", engine)
|
||||
self.state.vms = vms
|
||||
self.state.vms_loaded_at = time.time()
|
||||
self.state.vms_changed.emit()
|
||||
@@ -199,6 +205,85 @@ class Actions:
|
||||
|
||||
self.tasks.run(work, title="VMs laden", area="vm", on_success=success, on_error=self._netbox_failed)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Offline exchange files
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _default_export_name(self, kind):
|
||||
profile = (self.state.profile or {}).get("name", "export")
|
||||
safe = "".join(char if char.isalnum() or char in "-_" else "_" for char in profile)
|
||||
return f"{safe}-{kind}-{time.strftime('%Y%m%d-%H%M')}{exchange.FILE_SUFFIX}"
|
||||
|
||||
def export_file(self, vms=(), switches=()):
|
||||
"""Write VMs and/or ``(switch, snapshot)`` pairs to a JSON exchange file."""
|
||||
path, _filter = QFileDialog.getSaveFileName(
|
||||
self.window, "Für NetBox exportieren", self._default_export_name("vms" if vms else "switche"),
|
||||
f"NetBox-Synchronizer-Export (*{exchange.FILE_SUFFIX});;JSON (*.json)")
|
||||
if not path:
|
||||
return
|
||||
data = exchange.build_export(vms, switches, (self.state.profile or {}).get("name", ""))
|
||||
try:
|
||||
exchange.write_export(path, data)
|
||||
except OSError as error:
|
||||
widgets.error(self.window, "Export fehlgeschlagen", str(error))
|
||||
return
|
||||
parts = [f"{len(data['vms'])} VM(s)"] if data["vms"] else []
|
||||
parts += [f"{len(data['switches'])} Switch(e)"] if data["switches"] else []
|
||||
logger("vm" if vms else "switch").log(25, "Exportiert: %s → %s", ", ".join(parts), path)
|
||||
self.window.toast(f"{' und '.join(parts)} exportiert")
|
||||
|
||||
def _open_export(self):
|
||||
path, _filter = QFileDialog.getOpenFileName(
|
||||
self.window, "Exportdatei laden", "",
|
||||
f"NetBox-Synchronizer-Export (*{exchange.FILE_SUFFIX} *.json);;Alle Dateien (*)")
|
||||
if not path:
|
||||
return None
|
||||
try:
|
||||
return exchange.read_export(path)
|
||||
except (OSError, exchange.ExchangeError) as error:
|
||||
widgets.error(self.window, "Datei kann nicht geladen werden", str(error))
|
||||
return None
|
||||
|
||||
def _after_file_import(self):
|
||||
"""In online mode connect to NetBox so the loaded data can be imported right away."""
|
||||
if not self.state.offline and self.state.engine is None and self.state.netbox_configured():
|
||||
self.load_targets(on_done=self.state.vms_changed.emit)
|
||||
|
||||
def import_vms_file(self):
|
||||
data = self._open_export()
|
||||
if data is None:
|
||||
return
|
||||
if not data["vms"]:
|
||||
widgets.message(self.window, "Keine VMs enthalten", "Die Datei enthält keine virtuellen Maschinen.", "info")
|
||||
return
|
||||
self.state.vms = sorted(exchange.prepare_vms(data["vms"]), key=lambda item: item["name"].casefold())
|
||||
self.state.vms_loaded_at = time.time()
|
||||
self.state.vms_changed.emit()
|
||||
origin = f" (Profil „{data['profile']}“, {data.get('created', '')[:10]})" if data.get("profile") else ""
|
||||
logger("vm").log(25, "%d VM(s) aus Datei geladen%s", len(self.state.vms), origin)
|
||||
self.window.toast(f"{len(self.state.vms)} VM(s) aus Datei geladen")
|
||||
self._after_file_import()
|
||||
|
||||
def import_switches_file(self):
|
||||
if self.state.profile is None:
|
||||
return
|
||||
data = self._open_export()
|
||||
if data is None:
|
||||
return
|
||||
if not data["switches"]:
|
||||
widgets.message(self.window, "Keine Switche enthalten", "Die Datei enthält keine Switch-Daten.", "info")
|
||||
return
|
||||
snapshots, added = exchange.merge_switches(self.state.switches, data["switches"], lambda: uuid.uuid4().hex)
|
||||
for switch_id, snapshot in snapshots.items():
|
||||
self.state.switch_snapshots[switch_id] = snapshot
|
||||
self.state.switch_status[switch_id] = ("ok", "aus Datei · " + describe_snapshot(snapshot))
|
||||
if added:
|
||||
self.state.touch()
|
||||
self.state.switches_changed.emit()
|
||||
text = f"{len(snapshots)} Switch(e) aus Datei geladen" + (f", {added} neu im Profil" if added else "")
|
||||
logger("switch").log(25, "%s", text)
|
||||
self.window.toast(text)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Switches
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -274,9 +274,13 @@ class SwitchDialog(_Dialog):
|
||||
"""Edit one switch access."""
|
||||
|
||||
def __init__(self, parent, switch, devices=None):
|
||||
super().__init__(parent, "Switch bearbeiten", "SSH-Zugang zu einem bestehenden NetBox-Gerät.")
|
||||
self.switch = switch
|
||||
self.devices = {item["id"]: item for item in devices or []}
|
||||
# Without NetBox (offline mode) a switch is identified by its name only.
|
||||
self.manual = not self.devices and not switch.get("device_id")
|
||||
super().__init__(parent, "Switch bearbeiten" if switch.get("name") else "Switch hinzufügen",
|
||||
"SSH-Zugang zu einem Switch. Der Name muss dem späteren NetBox-Gerät entsprechen."
|
||||
if self.manual else "SSH-Zugang zu einem bestehenden NetBox-Gerät.")
|
||||
self.switch = switch
|
||||
self.result = None
|
||||
|
||||
form = QFormLayout()
|
||||
@@ -291,7 +295,12 @@ class SwitchDialog(_Dialog):
|
||||
form.addRow("NetBox-Gerät", self.device)
|
||||
else:
|
||||
self.device = None
|
||||
form.addRow("NetBox-Gerät", label(f"<b>{switch.get('name', '')}</b>"))
|
||||
if self.manual:
|
||||
self.name = QLineEdit(switch.get("name", ""))
|
||||
self.name.setPlaceholderText("Gerätename wie in NetBox")
|
||||
form.addRow("Name", self.name)
|
||||
else:
|
||||
form.addRow("NetBox-Gerät", label(f"<b>{switch.get('name', '')}</b>"))
|
||||
self.platform = _platform_combo(switch.get("platform", "auto"))
|
||||
self.host = QLineEdit(switch.get("host", ""))
|
||||
self.port = QSpinBox()
|
||||
@@ -323,19 +332,20 @@ class SwitchDialog(_Dialog):
|
||||
self.error_banner.show()
|
||||
|
||||
def accept(self):
|
||||
fields = (self.host, self.username, self.password)
|
||||
fields = (self.host, self.username, self.password) + ((self.name,) if self.manual else ())
|
||||
for widget in fields:
|
||||
_mark_invalid(widget, not widget.text().strip())
|
||||
device_id = self.device.valid_data() if self.device else self.switch.get("device_id")
|
||||
if self.device:
|
||||
_mark_invalid(self.device, device_id is None)
|
||||
if device_id is None or any(not widget.text().strip() for widget in fields):
|
||||
if (device_id is None and not self.manual) or any(not widget.text().strip() for widget in fields):
|
||||
self.show_error("Bitte Gerät und alle Zugangsdaten angeben.")
|
||||
return
|
||||
result = dict(self.switch)
|
||||
result.update({
|
||||
"device_id": device_id,
|
||||
"name": self.devices[device_id]["name"] if self.devices else self.switch.get("name", ""),
|
||||
"name": (self.name.text().strip() if self.manual else
|
||||
self.devices[device_id]["name"] if self.devices else self.switch.get("name", "")),
|
||||
"platform": self.platform.currentData(),
|
||||
"host": self.host.text().strip(),
|
||||
"port": self.port.value(),
|
||||
|
||||
@@ -114,6 +114,7 @@ class MainWindow(QMainWindow):
|
||||
self.state.profile_switched.connect(self._refresh_profiles)
|
||||
self.state.netbox_changed.connect(self._refresh_netbox_pill)
|
||||
self.state.profile_edited.connect(self._refresh_netbox_pill)
|
||||
self.state.settings_changed.connect(self._settings_changed)
|
||||
self.state.save_failed.connect(lambda text: self.toast(f"Speichern fehlgeschlagen: {text}", "error", 8000))
|
||||
theme.changed.connect(self._theme_changed)
|
||||
|
||||
@@ -124,7 +125,8 @@ class MainWindow(QMainWindow):
|
||||
|
||||
self._restore_geometry()
|
||||
self.state.load()
|
||||
self.navigate("overview" if self.state.profile is None or not self.state.netbox_configured() else "vms")
|
||||
self.navigate("overview" if self.state.profile is None
|
||||
or not (self.state.offline or self.state.netbox_configured()) else "vms")
|
||||
self._busy_changed(False)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -185,7 +187,14 @@ class MainWindow(QMainWindow):
|
||||
self.profile_menu_button.setMenu(menu)
|
||||
profile_row.addWidget(self.profile_menu_button)
|
||||
layout.addLayout(profile_row)
|
||||
layout.addSpacing(20)
|
||||
layout.addSpacing(8)
|
||||
self.offline_check = widgets.checkbox(
|
||||
"Offline-Modus (ohne NetBox)",
|
||||
tooltip="VMs und Switche nur auslesen und als JSON-Datei exportieren. Die Datei lässt sich später auf "
|
||||
"einem Rechner mit NetBox-Zugang über „Aus Datei laden …“ importieren.")
|
||||
self.offline_check.toggled.connect(lambda value: self.state.update_settings(offline_mode=value))
|
||||
layout.addWidget(self.offline_check)
|
||||
layout.addSpacing(14)
|
||||
|
||||
self.nav_group = QButtonGroup(self)
|
||||
self.nav_group.setExclusive(True)
|
||||
@@ -290,6 +299,7 @@ class MainWindow(QMainWindow):
|
||||
for action in self.profile_actions.values():
|
||||
action.setEnabled(not busy)
|
||||
self.profile_combo.setEnabled(not busy)
|
||||
self.offline_check.setEnabled(not busy)
|
||||
|
||||
def _progress(self, value, maximum, text):
|
||||
if maximum:
|
||||
@@ -304,8 +314,17 @@ class MainWindow(QMainWindow):
|
||||
self.cancel_button.setEnabled(False)
|
||||
self.task_label.setText("Wird abgebrochen …")
|
||||
|
||||
def _settings_changed(self):
|
||||
self.offline_check.blockSignals(True)
|
||||
self.offline_check.setChecked(self.state.offline)
|
||||
self.offline_check.blockSignals(False)
|
||||
self._refresh_netbox_pill()
|
||||
|
||||
def _refresh_netbox_pill(self):
|
||||
if self.state.profile is None or not self.state.netbox_configured():
|
||||
self.netbox_pill.setToolTip("")
|
||||
if self.state.offline:
|
||||
self.netbox_pill.set("Offline-Modus · Export per JSON", "neutral")
|
||||
elif self.state.profile is None or not self.state.netbox_configured():
|
||||
self.netbox_pill.set("NetBox: nicht eingerichtet", "warning")
|
||||
elif self.state.netbox_status == "ok":
|
||||
self.netbox_pill.set(f"NetBox {self.state.netbox_version} · verbunden", "success")
|
||||
|
||||
@@ -133,7 +133,7 @@ class OverviewPage(Page):
|
||||
self.body.addWidget(self.content, 1)
|
||||
|
||||
for signal in (self.state.profile_switched, self.state.profile_edited, self.state.netbox_changed,
|
||||
self.state.vms_changed, self.state.switches_changed):
|
||||
self.state.vms_changed, self.state.switches_changed, self.state.settings_changed):
|
||||
signal.connect(self.refresh)
|
||||
self.refresh()
|
||||
|
||||
@@ -155,7 +155,10 @@ class OverviewPage(Page):
|
||||
|
||||
configured = self.state.netbox_configured()
|
||||
status = self.state.netbox_status
|
||||
if not configured:
|
||||
if self.state.offline:
|
||||
self.netbox_tile.set("Offline-Modus", "Daten werden als JSON-Datei exportiert statt nach NetBox "
|
||||
"geschrieben.", "Offline", "neutral")
|
||||
elif not configured:
|
||||
self.netbox_tile.set("Nicht eingerichtet", "URL und API-Token fehlen.", "Einrichten", "warning")
|
||||
elif status == "ok":
|
||||
self.netbox_tile.set(f"NetBox {self.state.netbox_version}", profile["netbox_url"], "Verbunden", "success")
|
||||
@@ -168,7 +171,8 @@ class OverviewPage(Page):
|
||||
active = sum(1 for source in sources if source.get("enabled", True))
|
||||
if self.state.vms:
|
||||
new = sum(1 for vm in self.state.vms if self.state.engine and vm["name"] not in self.state.engine.existing_vms)
|
||||
self.vm_tile.set(f"{len(self.state.vms)} VMs", f"{new} noch nicht in NetBox · geladen {_ago(self.state.vms_loaded_at)}",
|
||||
known = "" if self.state.engine is None else f"{new} noch nicht in NetBox · "
|
||||
self.vm_tile.set(f"{len(self.state.vms)} VMs", f"{known}geladen {_ago(self.state.vms_loaded_at)}",
|
||||
f"{active} Quelle(n)", "info")
|
||||
else:
|
||||
self.vm_tile.set(f"{len(sources)} Quelle(n)", "VMs noch nicht geladen." if sources else "Noch keine Quelle.",
|
||||
@@ -181,7 +185,7 @@ class OverviewPage(Page):
|
||||
self.switch_tile.set(f"{len(switches)} Switch(e)", detail,
|
||||
f"{errors} Fehler" if errors else "", "error" if errors else "neutral")
|
||||
|
||||
done = [configured and status != "error", bool(sources), bool(self.state.vms), bool(switches)]
|
||||
done = [self.state.offline or (configured and status != "error"), bool(sources), bool(self.state.vms), bool(switches)]
|
||||
first_open = next((index for index, value in enumerate(done) if not value), None)
|
||||
for index, step in enumerate(self.steps):
|
||||
step.set_done(done[index], primary=index == first_open)
|
||||
@@ -1,4 +1,5 @@
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
|
||||
@@ -77,6 +78,9 @@ class SwitchesPage(Page):
|
||||
|
||||
# Results -------------------------------------------------------------
|
||||
result_card = Card("Ergebnisse", "Erkannte Schnittstellen und Nachbarn der ausgelesenen Switche.")
|
||||
self.file_button = result_card.add_action(button("Aus Datei laden …", "folder", on_click=self.load_file,
|
||||
tooltip="Ausleseergebnisse aus einer im Offline-Modus "
|
||||
"erstellten Exportdatei (JSON) laden."))
|
||||
self.raw_button = result_card.add_action(button("SSH-Rohdaten", "terminal", on_click=self.show_raw))
|
||||
self.sync_button = result_card.add_action(button("Nach NetBox übertragen …", "upload", "primary",
|
||||
on_click=self.sync))
|
||||
@@ -142,6 +146,7 @@ class SwitchesPage(Page):
|
||||
self.state.profile_switched.connect(self.refresh)
|
||||
self.state.profile_edited.connect(self.refresh_switches)
|
||||
self.state.settings_changed.connect(self._load_settings)
|
||||
self.state.settings_changed.connect(self._update_buttons)
|
||||
self._load_settings()
|
||||
self.refresh()
|
||||
|
||||
@@ -234,11 +239,18 @@ class SwitchesPage(Page):
|
||||
self.discover_button.setText(f"{len(targets)} auslesen" if targets else "Auslesen")
|
||||
widgets.set_enabled(self.sync_button, bool(with_data) and not busy,
|
||||
"Bitte zuerst Switche auslesen." if not with_data else "Bitte warten …")
|
||||
self.sync_button.setText(f"{len(with_data)} nach NetBox übertragen …" if with_data else "Nach NetBox übertragen …")
|
||||
offline = self.state.offline
|
||||
if offline:
|
||||
self.sync_button.setText(f"{len(with_data)} exportieren …" if with_data else "Exportieren …")
|
||||
else:
|
||||
self.sync_button.setText(f"{len(with_data)} nach NetBox übertragen …" if with_data
|
||||
else "Nach NetBox übertragen …")
|
||||
self.cables_option.setVisible(not offline)
|
||||
widgets.set_enabled(self.raw_button, bool(self.state.switch_snapshots), "Noch nichts ausgelesen.")
|
||||
widgets.set_enabled(self.edit_button, len(self._selected()) == 1, "Bitte genau einen Switch markieren.")
|
||||
widgets.set_enabled(self.remove_button, bool(targets), "Bitte Switche anhaken oder markieren.")
|
||||
self.add_button.setEnabled(not busy)
|
||||
self.file_button.setEnabled(not busy)
|
||||
|
||||
def set_busy(self, busy):
|
||||
self._update_buttons()
|
||||
@@ -266,7 +278,16 @@ class SwitchesPage(Page):
|
||||
self.switch_model.set_checked({switch["id"] for switch in dialog.result})
|
||||
self.window.toast(f"{len(dialog.result)} Switch(e) hinzugefügt – jetzt „Auslesen“ wählen")
|
||||
|
||||
if self.state.netbox_devices is not None:
|
||||
if self.state.offline:
|
||||
dialog = SwitchDialog(self.window, {"id": uuid.uuid4().hex, "platform": "auto", "port": 22,
|
||||
"enabled": True})
|
||||
if dialog.exec() and dialog.result:
|
||||
self.state.switches.append(dialog.result)
|
||||
self.state.touch()
|
||||
self.refresh_switches()
|
||||
self.switch_model.set_checked({dialog.result["id"]})
|
||||
self.window.toast(f"{dialog.result['name']} hinzugefügt – jetzt „Auslesen“ wählen")
|
||||
elif self.state.netbox_devices is not None:
|
||||
open_dialog(self.state.netbox_devices)
|
||||
else:
|
||||
self.actions.load_devices(open_dialog)
|
||||
@@ -314,7 +335,16 @@ class SwitchesPage(Page):
|
||||
return
|
||||
self.actions.discover_switches(targets)
|
||||
|
||||
def load_file(self):
|
||||
self.actions.import_switches_file()
|
||||
|
||||
def sync(self):
|
||||
if self.state.offline:
|
||||
pairs = [(switch, self.state.switch_snapshots[switch["id"]]) for switch in self._targets()
|
||||
if switch["id"] in self.state.switch_snapshots]
|
||||
if pairs:
|
||||
self.actions.export_file(switches=pairs)
|
||||
return
|
||||
targets = [switch["id"] for switch in self._targets() if switch["id"] in self.state.switch_snapshots]
|
||||
self.actions.sync_switches(targets, self.cables_option.isChecked())
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ class VMsPage(Page):
|
||||
|
||||
def __init__(self, window):
|
||||
super().__init__(window)
|
||||
self.file_button = self.header.add_action(button("Aus Datei laden …", "folder", on_click=self.load_file,
|
||||
tooltip="VMs aus einer im Offline-Modus erstellten "
|
||||
"Exportdatei (JSON) laden."))
|
||||
self.load_button = self.header.add_action(button("VMs laden", "refresh", "primary", on_click=self.load))
|
||||
|
||||
self.stack = QStackedWidget()
|
||||
@@ -105,6 +108,8 @@ class VMsPage(Page):
|
||||
self.model.checked_changed.connect(self._update_selection)
|
||||
self.state.vms_changed.connect(self.refresh)
|
||||
self.state.profile_switched.connect(self.refresh)
|
||||
self.state.settings_changed.connect(self.refresh)
|
||||
self.state.netbox_changed.connect(self.refresh)
|
||||
self.refresh()
|
||||
|
||||
def _netbox_state(self, vm):
|
||||
@@ -114,6 +119,11 @@ class VMsPage(Page):
|
||||
return "Vorhanden" if vm["name"] in engine.existing_vms else "Neu"
|
||||
|
||||
def refresh(self):
|
||||
offline = self.state.offline
|
||||
self.table.setColumnHidden(1, offline)
|
||||
self.netbox_filter.setVisible(not offline)
|
||||
if offline and self.netbox_filter.currentIndex():
|
||||
self.netbox_filter.setCurrentIndex(0)
|
||||
vms = self.state.vms
|
||||
self.stack.setCurrentIndex(1 if vms else 0)
|
||||
current = self.source_filter.currentData()
|
||||
@@ -128,7 +138,13 @@ class VMsPage(Page):
|
||||
self._apply_filters()
|
||||
self.load_button.setText("Neu laden" if vms else "VMs laden")
|
||||
if not vms:
|
||||
if not self.state.netbox_configured():
|
||||
if offline and not self.state.sources:
|
||||
self.empty.set_text(text="Offline-Modus: Unter „Verbindungen“ eine VMware- oder Proxmox-Quelle "
|
||||
"einrichten oder eine Exportdatei laden.")
|
||||
elif offline:
|
||||
self.empty.set_text(text="Offline-Modus: Die Quellen werden ohne NetBox ausgelesen; ausgewählte VMs "
|
||||
"lassen sich anschließend als JSON-Datei exportieren.")
|
||||
elif not self.state.netbox_configured():
|
||||
self.empty.set_text(text="Zuerst unter „Verbindungen“ NetBox und mindestens eine Quelle einrichten.")
|
||||
elif not self.state.sources:
|
||||
self.empty.set_text(text="Es ist noch keine VMware- oder Proxmox-Quelle hinterlegt.")
|
||||
@@ -169,24 +185,34 @@ class VMsPage(Page):
|
||||
total = len(self.model.rows)
|
||||
shown = f"{visible} von {total} angezeigt" if visible != total else f"{total} VMs"
|
||||
self.selection_label.setText(f"{shown} · {count} ausgewählt")
|
||||
self.import_button.setText(f"{count} VM(s) importieren …" if count else "Importieren …")
|
||||
verb = "exportieren" if self.state.offline else "importieren"
|
||||
self.import_button.setText(f"{count} VM(s) {verb} …" if count else f"{verb.capitalize()} …")
|
||||
self._update_import_button()
|
||||
|
||||
def _update_import_button(self):
|
||||
count = len(self.model.checked)
|
||||
enabled = count > 0 and not self.tasks.busy and self.state.engine is not None
|
||||
widgets.set_enabled(self.import_button, enabled,
|
||||
"Bitte zuerst VMs in der Tabelle anhaken." if not count else "Bitte warten …")
|
||||
ready = self.state.offline or self.state.engine is not None
|
||||
enabled = count > 0 and not self.tasks.busy and ready
|
||||
reason = ("Bitte zuerst VMs in der Tabelle anhaken." if not count else
|
||||
"Bitte warten …" if self.tasks.busy else "Keine Verbindung zu NetBox – „Neu laden“ wählen.")
|
||||
widgets.set_enabled(self.import_button, enabled, reason)
|
||||
|
||||
def set_busy(self, busy):
|
||||
self.load_button.setEnabled(not busy)
|
||||
self.file_button.setEnabled(not busy)
|
||||
self._update_import_button()
|
||||
|
||||
def load(self):
|
||||
self.actions.load_vms()
|
||||
|
||||
def load_file(self):
|
||||
self.actions.import_vms_file()
|
||||
|
||||
def start_import(self):
|
||||
vms = self.model.checked_rows()
|
||||
if vms and self.state.offline:
|
||||
self.actions.export_file(vms=vms)
|
||||
return
|
||||
if not vms or self.state.engine is None:
|
||||
return
|
||||
wizard = ImportWizard(self.window, self.state, self.tasks, vms)
|
||||
|
||||
@@ -190,6 +190,10 @@ class AppState(QObject):
|
||||
def switches(self):
|
||||
return self.profile["switches"] if self.profile else []
|
||||
|
||||
@property
|
||||
def offline(self):
|
||||
return bool(self.settings.get("offline_mode"))
|
||||
|
||||
def netbox_configured(self):
|
||||
profile = self.profile
|
||||
return bool(profile and profile.get("netbox_url") and profile.get("netbox_token"))
|
||||
@@ -78,6 +78,7 @@ QToolTip { background: $text; color: $surface; border: none; padding: 6px 8px; b
|
||||
/* ---------- Sidebar ---------- */
|
||||
#Sidebar { background: $sidebar; }
|
||||
#Sidebar QLabel { color: $sidebar_text; }
|
||||
#Sidebar QCheckBox { color: $sidebar_text; background: transparent; }
|
||||
#Sidebar #AppTitle { color: #FFFFFF; font-size: 12pt; font-weight: 600; }
|
||||
#Sidebar #AppSubtitle { color: $sidebar_text; font-size: 8.5pt; }
|
||||
#Sidebar #SectionLabel { color: #6B7FA0; font-size: 8pt; font-weight: 600; }
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from netbox_sync.core import exchange
|
||||
|
||||
|
||||
def _vm(**values):
|
||||
vm = {"id": "src:0:web01", "source_id": "src", "name": "web01", "source": "vcenter", "source_type": "VMware",
|
||||
"kind": "VM", "status": "active", "vcpus": 2, "memory": 4096, "disk": 51200, "guest_os": "Linux",
|
||||
"cluster": "CL1", "interfaces": [{"name": "eth0", "mac": "00:50:56:00:00:01", "ips": ["10.0.0.5/24"]}]}
|
||||
vm.update(values)
|
||||
return vm
|
||||
|
||||
|
||||
def _switch(**values):
|
||||
switch = {"id": "s1", "name": "sw01", "device_id": 7, "platform": "aruba_cx", "host": "10.0.0.2", "port": 22,
|
||||
"username": "admin", "password": "geheim", "enabled": True}
|
||||
switch.update(values)
|
||||
return switch
|
||||
|
||||
|
||||
SNAPSHOT = {"platform": "aruba_cx", "interfaces": [{"name": "1/1/1"}], "discovered_at": 1.0}
|
||||
|
||||
|
||||
def test_round_trip_strips_credentials(tmp_path):
|
||||
path = tmp_path / "export.nbsync.json"
|
||||
exchange.write_export(path, exchange.build_export([_vm()], [(_switch(), SNAPSHOT)], "Kunde"))
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert "geheim" not in text and "admin" not in text
|
||||
data = exchange.read_export(path)
|
||||
assert data["profile"] == "Kunde"
|
||||
assert "id" not in data["vms"][0] and data["vms"][0]["cluster"] == "CL1"
|
||||
assert data["switches"][0]["switch"] == {"id": "s1", "name": "sw01", "device_id": 7, "platform": "aruba_cx",
|
||||
"host": "10.0.0.2", "port": 22}
|
||||
|
||||
|
||||
def test_prepare_vms_assigns_runtime_ids():
|
||||
vms = exchange.prepare_vms([{"name": "a", "source": "vc"}, {"name": "a", "source": "vc"}])
|
||||
assert vms[0]["source_id"] == "file:vc"
|
||||
assert vms[0]["id"] != vms[1]["id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
{"format": "other"},
|
||||
{"format": exchange.FORMAT, "version": exchange.FORMAT_VERSION + 1},
|
||||
{"format": exchange.FORMAT, "version": 1, "vms": [{"name": "x"}]},
|
||||
{"format": exchange.FORMAT, "version": 1, "switches": [{"switch": {"name": "x"}}]},
|
||||
])
|
||||
def test_invalid_files_are_rejected(tmp_path, payload):
|
||||
path = tmp_path / "bad.json"
|
||||
path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
with pytest.raises(exchange.ExchangeError):
|
||||
exchange.read_export(path)
|
||||
|
||||
|
||||
def test_merge_switches_matches_by_device_then_name():
|
||||
profile = [_switch(id="a", device_id=7, name="old-name"), _switch(id="b", device_id=None, name="SW02")]
|
||||
items = [
|
||||
{"switch": {"name": "sw01", "device_id": 7}, "snapshot": {"n": 1}},
|
||||
{"switch": {"name": "sw02"}, "snapshot": {"n": 2}},
|
||||
{"switch": {"name": "sw03", "host": "10.0.0.3"}, "snapshot": {"n": 3}},
|
||||
]
|
||||
snapshots, added = exchange.merge_switches(profile, items, lambda: "new")
|
||||
assert snapshots == {"a": {"n": 1}, "b": {"n": 2}, "new": {"n": 3}}
|
||||
assert added == 1
|
||||
assert profile[-1]["name"] == "sw03" and profile[-1]["enabled"] is False and profile[-1]["password"] == ""
|
||||
@@ -52,3 +52,14 @@ def test_sync_matches_short_names_and_keeps_existing_types():
|
||||
nb.dcim.interfaces.get(1).cable = True
|
||||
again = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=True, dry_run=True)
|
||||
assert again["changes"] == []
|
||||
|
||||
|
||||
def test_offline_switch_is_resolved_by_name():
|
||||
nb, _switch, snapshot = _setup()
|
||||
report = sync_snapshot_to_netbox(nb, {"id": "s", "name": "access-01", "device_id": None}, snapshot,
|
||||
create_cables=False, dry_run=True)
|
||||
assert report["errors"] == []
|
||||
assert report["interfaces_unchanged"] == 1
|
||||
|
||||
missing = sync_snapshot_to_netbox(nb, {"id": "s", "name": "unbekannt"}, snapshot, dry_run=True)
|
||||
assert missing["errors"] == ["NetBox-Gerät „unbekannt“ nicht gefunden"]
|
||||
Reference in new issue
Block a user