From c6a7f615f565819d0c599d96f3928110dd4f69eb Mon Sep 17 00:00:00 2001 From: Alexis COURTEILLE Date: Wed, 4 Nov 2026 14:46:59 +0100 Subject: [PATCH] Make VLAN reconciles create-only so existing NetBox VLANs are not rewritten Node and VM interface sync reconciled /api/ipam/vlans/ by VID with a hard-coded payload (name "VLAN ", status active, Proxbox tags) and no patchable_fields. Every pre-existing VLAN whose VID appeared on an interface was therefore renamed, forced to active and re-tagged on the first sync. Pass NETBOX_VLAN_PATCHABLE_FIELDS (an empty set) to all eight VLAN reconciles: missing VLANs are still created as "VLAN ", existing ones are only linked. A static test guards future VLAN call sites. Co-Authored-By: Claude Opus 5.5 --- docs/pt-BR/sync/workflows.md | 8 + docs/sync/workflows.md | 7 + proxbox_api/proxmox_to_netbox/models.py | 6 + .../virtual_machines/sync_vm.py | 2 + .../sync/individual/interface_sync.py | 2 + proxbox_api/services/sync/network.py | 5 + proxbox_api/services/sync/vm_network.py | 2 + .../services/sync/vm_network_processor.py | 6 +- tests/test_vlan_reconcile_create_only.py | 157 ++++++++++++++++++ 9 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 tests/test_vlan_reconcile_create_only.py diff --git a/docs/pt-BR/sync/workflows.md b/docs/pt-BR/sync/workflows.md index 4ba15f7d..65ec73d2 100644 --- a/docs/pt-BR/sync/workflows.md +++ b/docs/pt-BR/sync/workflows.md @@ -145,6 +145,14 @@ vez de serem limpos, entao uma falha transitoria nao apaga atribuicoes de VLAN. As demais interfaces continuam tendo a topologia obsoleta limpa quando o Proxmox a remove. +As escritas de VLAN sao somente de criacao. O Proxmox so conhece uma VLAN pelo +seu VID; quando uma interface de no ou de VM carrega um VID ausente no NetBox, o +sync cria `VLAN `; quando uma VLAN com esse VID ja existe, a interface e +ligada a ela e a VLAN em si nao e alterada (nome, status e tags nunca recebem +patch). Toda reconciliacao de VLAN passa `NETBOX_VLAN_PATCHABLE_FIELDS` (um +conjunto vazio), e `tests/test_vlan_reconcile_create_only.py` protege novos +pontos de chamada. + ## Fluxo de Sync de VM Endpoint principal: diff --git a/docs/sync/workflows.md b/docs/sync/workflows.md index 45bfa4ff..1294c7db 100644 --- a/docs/sync/workflows.md +++ b/docs/sync/workflows.md @@ -141,6 +141,13 @@ sub-interface cannot be reconciled, the interface keeps its existing NetBox being cleared, so a transient failure cannot erase VLAN assignments. Other interfaces still have stale topology cleared when Proxmox removes it. +VLAN writes are create-only. Proxmox only knows a VLAN by its VID, so when a +node or VM interface carries a VID that is missing from NetBox, the sync creates +`VLAN `; when a VLAN with that VID already exists, the interface is linked +to it and the VLAN itself is left untouched (name, status and tags are never +patched). Every VLAN reconcile passes `NETBOX_VLAN_PATCHABLE_FIELDS` (an empty +set), and `tests/test_vlan_reconcile_create_only.py` guards new call sites. + ## Virtual Machine Sync Flow Primary endpoint: diff --git a/proxbox_api/proxmox_to_netbox/models.py b/proxbox_api/proxmox_to_netbox/models.py index cf45827f..d47a9ac3 100644 --- a/proxbox_api/proxmox_to_netbox/models.py +++ b/proxbox_api/proxmox_to_netbox/models.py @@ -508,6 +508,12 @@ def normalize_tags(cls, value: object) -> list[dict[str, object]]: return _normalized_tag_list(value) +# VLANs are operator-owned in NetBox: Proxmox only knows a VID, so the sync +# creates a missing ``VLAN `` but must never rename, re-status or re-tag +# an existing VLAN that it merely links an interface to. +NETBOX_VLAN_PATCHABLE_FIELDS: frozenset[str] = frozenset() + + class NetBoxBackupSyncState(BaseModel): model_config = ConfigDict(extra="forbid", populate_by_name=True) diff --git a/proxbox_api/routes/virtualization/virtual_machines/sync_vm.py b/proxbox_api/routes/virtualization/virtual_machines/sync_vm.py index 07c19700..2098d33d 100644 --- a/proxbox_api/routes/virtualization/virtual_machines/sync_vm.py +++ b/proxbox_api/routes/virtualization/virtual_machines/sync_vm.py @@ -38,6 +38,7 @@ ) from proxbox_api.netbox_version import detect_netbox_version, supports_virtual_machine_type from proxbox_api.proxmox_to_netbox.models import ( + NETBOX_VLAN_PATCHABLE_FIELDS, NetBoxDeviceRoleSyncState, NetBoxVirtualDiskSyncState, NetBoxVirtualMachineCreateBody, @@ -2403,6 +2404,7 @@ async def _create_vm_interface_parallel( "tags": tag_refs, }, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda record: { "vid": record.get("vid"), "name": record.get("name"), diff --git a/proxbox_api/services/sync/individual/interface_sync.py b/proxbox_api/services/sync/individual/interface_sync.py index 396fe146..0caa53cc 100644 --- a/proxbox_api/services/sync/individual/interface_sync.py +++ b/proxbox_api/services/sync/individual/interface_sync.py @@ -7,6 +7,7 @@ from proxbox_api.logger import logger from proxbox_api.netbox_rest import rest_reconcile_async from proxbox_api.proxmox_to_netbox.models import ( + NETBOX_VLAN_PATCHABLE_FIELDS, NetBoxVirtualMachineInterfaceSyncState, NetBoxVlanSyncState, ) @@ -94,6 +95,7 @@ async def _resolve_vlan_id( "tags": tag_refs, }, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda record: { "vid": record.get("vid"), "name": record.get("name"), diff --git a/proxbox_api/services/sync/network.py b/proxbox_api/services/sync/network.py index 4bc66d9b..929f2f41 100644 --- a/proxbox_api/services/sync/network.py +++ b/proxbox_api/services/sync/network.py @@ -22,6 +22,7 @@ ) from proxbox_api.proxmox_async import resolve_async from proxbox_api.proxmox_to_netbox.models import ( + NETBOX_VLAN_PATCHABLE_FIELDS, NetBoxInterfaceSyncState, NetBoxIpAddressSyncState, NetBoxVirtualMachineInterfaceSyncState, @@ -325,6 +326,7 @@ async def _sync_legacy_node_vlan( "tags": tag_refs, }, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda row: { "vid": row.get("vid"), "name": row.get("name"), @@ -569,6 +571,7 @@ async def _sync_node_interface_vlan( lookup={"vid": vid}, payload={"vid": vid, "name": f"VLAN {vid}", "status": "active", "tags": tag_refs}, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda row: { "vid": row.get("vid"), "name": row.get("name"), @@ -1050,6 +1053,7 @@ async def _resolve_vm_interface_vlan( "tags": tag_refs, }, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda record: { "vid": record.get("vid"), "name": record.get("name"), @@ -1223,6 +1227,7 @@ async def bulk_reconcile_vlans( # the reconcile can match/patch the wrong VLAN (or recreate one). lookup_query_field_map={"site": "site_id", "tenant": "tenant_id"}, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda record: { "vid": record.get("vid"), "name": record.get("name"), diff --git a/proxbox_api/services/sync/vm_network.py b/proxbox_api/services/sync/vm_network.py index ed7bc614..df3c7ca5 100644 --- a/proxbox_api/services/sync/vm_network.py +++ b/proxbox_api/services/sync/vm_network.py @@ -15,6 +15,7 @@ rest_reconcile_async, ) from proxbox_api.proxmox_to_netbox.models import ( + NETBOX_VLAN_PATCHABLE_FIELDS, NetBoxVirtualDiskSyncState, NetBoxVirtualMachineInterfaceSyncState, NetBoxVlanSyncState, @@ -171,6 +172,7 @@ async def sync_vm_interfaces( # noqa: C901 "tags": tag_refs, }, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda record: { "vid": record.get("vid"), "name": record.get("name"), diff --git a/proxbox_api/services/sync/vm_network_processor.py b/proxbox_api/services/sync/vm_network_processor.py index 7baa1e09..f1751491 100644 --- a/proxbox_api/services/sync/vm_network_processor.py +++ b/proxbox_api/services/sync/vm_network_processor.py @@ -7,7 +7,10 @@ from proxbox_api.dependencies import NetBoxSessionDep from proxbox_api.logger import logger from proxbox_api.netbox_rest import rest_reconcile_async -from proxbox_api.proxmox_to_netbox.models import NetBoxVlanSyncState +from proxbox_api.proxmox_to_netbox.models import ( + NETBOX_VLAN_PATCHABLE_FIELDS, + NetBoxVlanSyncState, +) from proxbox_api.services.sync.vm_helpers import merged_guest_iface_from_mac_index @@ -126,6 +129,7 @@ async def process_vm_network_interface( # noqa: C901 "tags": tag_refs, }, schema=NetBoxVlanSyncState, + patchable_fields=NETBOX_VLAN_PATCHABLE_FIELDS, current_normalizer=lambda record: { "vid": record.get("vid"), "name": record.get("name"), diff --git a/tests/test_vlan_reconcile_create_only.py b/tests/test_vlan_reconcile_create_only.py new file mode 100644 index 00000000..1bd88e02 --- /dev/null +++ b/tests/test_vlan_reconcile_create_only.py @@ -0,0 +1,157 @@ +"""Regression tests: VLAN reconciles are create-only. + +Proxmox only knows a VLAN by its VID. When an interface carries a VID that +already exists in NetBox, the sync must *link* to that VLAN, never rewrite it: +before the fix, every existing VLAN matched by VID was renamed to +``VLAN ``, forced to ``active`` and had its tags replaced by the Proxbox +tag, because the VLAN reconciles passed no ``patchable_fields``. +""" + +from __future__ import annotations + +import ast +from pathlib import Path +from typing import Any + +import pytest + +from proxbox_api import netbox_rest +from proxbox_api.proxmox_to_netbox.models import NETBOX_VLAN_PATCHABLE_FIELDS +from proxbox_api.services.sync import network + +ROOT = Path(__file__).parent.parent +_VLAN_PATH = "/api/ipam/vlans/" +_PROXBOX_TAG: list[dict[str, object]] = [ + {"id": 5, "name": "Proxbox", "slug": "proxbox", "color": "ff5722"}, +] + + +class _FakeRecord: + """Existing NetBox record: tracks PATCH traffic through ``save()``.""" + + def __init__(self, payload: dict[str, Any], record_id: int) -> None: + object.__setattr__(self, "_payload", dict(payload)) + object.__setattr__(self, "id", record_id) + object.__setattr__(self, "save_calls", 0) + object.__setattr__(self, "patched_fields", {}) + + def serialize(self) -> dict[str, Any]: + return {**self._payload, "id": self.id} + + def get(self, key: str, default: Any = None) -> Any: + return self._payload.get(key, default) + + async def save(self) -> None: + object.__setattr__(self, "save_calls", self.save_calls + 1) + + def __setattr__(self, key: str, value: Any) -> None: + if key in {"_payload", "id", "save_calls", "patched_fields"}: + object.__setattr__(self, key, value) + return + self.patched_fields[key] = value + + +@pytest.fixture +def fake_netbox(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """Fake the REST seams used by ``rest_reconcile_async``.""" + state: dict[str, Any] = {"existing": None, "posts": []} + + async def _fake_first(_nb: object, _path: str, *, query: dict[str, Any]) -> Any: + del query + return state["existing"] + + async def _fake_create(_nb: object, _path: str, payload: dict[str, Any], **_kw: Any) -> Any: + state["posts"].append(dict(payload)) + return _FakeRecord(payload, record_id=99) + + monkeypatch.setattr(netbox_rest, "rest_first_async", _fake_first) + monkeypatch.setattr(netbox_rest, "rest_create_async", _fake_create) + return state + + +def _node_vlan_entry(vid: int) -> dict[str, Any]: + return {"type": "vlan", "vlan-id": str(vid), "vlan-raw-device": "bond0"} + + +def test_vlan_patchable_fields_is_empty() -> None: + assert NETBOX_VLAN_PATCHABLE_FIELDS == frozenset() + + +async def test_existing_vlan_is_linked_without_being_modified( + fake_netbox: dict[str, Any], +) -> None: + existing = _FakeRecord( + {"vid": 198, "name": "DEV_COMMON", "status": "reserved", "tags": []}, + record_id=15, + ) + fake_netbox["existing"] = existing + failures: list[dict] = [] + + vlan_id = await network._sync_node_interface_vlan( + object(), + {"id": 1, "name": "node1"}, + _node_vlan_entry(198), + "bond0.198", + _PROXBOX_TAG, + failures, + ) + + assert vlan_id == 15 + assert existing.save_calls == 0 + assert existing.patched_fields == {} + assert fake_netbox["posts"] == [] + assert failures == [] + + +async def test_missing_vlan_is_still_created(fake_netbox: dict[str, Any]) -> None: + failures: list[dict] = [] + + vlan_id = await network._sync_node_interface_vlan( + object(), + {"id": 1, "name": "node1"}, + _node_vlan_entry(1842), + "bond0.1842", + _PROXBOX_TAG, + failures, + ) + + assert vlan_id == 99 + assert len(fake_netbox["posts"]) == 1 + created = fake_netbox["posts"][0] + assert created["vid"] == 1842 + assert created["name"] == "VLAN 1842" + assert failures == [] + + +def _vlan_reconcile_calls() -> list[tuple[str, int, ast.Call]]: + calls: list[tuple[str, int, ast.Call]] = [] + for path in sorted((ROOT / "proxbox_api").rglob("*.py")): + if "generated" in path.parts: + continue + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None) + if name not in {"rest_reconcile_async", "rest_bulk_reconcile_async"}: + continue + if len(node.args) < 2: + continue + target = node.args[1] + if isinstance(target, ast.Constant) and target.value == _VLAN_PATH: + calls.append((str(path.relative_to(ROOT)), node.lineno, node)) + return calls + + +def test_every_vlan_reconcile_is_create_only() -> None: + """Guard future call sites: any VLAN reconcile must pass the create-only set.""" + calls = _vlan_reconcile_calls() + assert calls, "expected VLAN reconcile call sites" + offenders = [] + for rel_path, lineno, call in calls: + keywords = {kw.arg: kw.value for kw in call.keywords} + value = keywords.get("patchable_fields") + if not (isinstance(value, ast.Name) and value.id == "NETBOX_VLAN_PATCHABLE_FIELDS"): + offenders.append(f"{rel_path}:{lineno}") + assert offenders == []