Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/pt-BR/sync/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <vid>`; 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:
Expand Down
7 changes: 7 additions & 0 deletions docs/sync/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <vid>`; 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:
Expand Down
6 changes: 6 additions & 0 deletions proxbox_api/proxmox_to_netbox/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <vid>`` 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)

Expand Down
2 changes: 2 additions & 0 deletions proxbox_api/routes/virtualization/virtual_machines/sync_vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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"),
Expand Down
2 changes: 2 additions & 0 deletions proxbox_api/services/sync/individual/interface_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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"),
Expand Down
5 changes: 5 additions & 0 deletions proxbox_api/services/sync/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),
Expand Down
2 changes: 2 additions & 0 deletions proxbox_api/services/sync/vm_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
rest_reconcile_async,
)
from proxbox_api.proxmox_to_netbox.models import (
NETBOX_VLAN_PATCHABLE_FIELDS,
NetBoxVirtualDiskSyncState,
NetBoxVirtualMachineInterfaceSyncState,
NetBoxVlanSyncState,
Expand Down Expand Up @@ -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"),
Expand Down
6 changes: 5 additions & 1 deletion proxbox_api/services/sync/vm_network_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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"),
Expand Down
157 changes: 157 additions & 0 deletions tests/test_vlan_reconcile_create_only.py
Original file line number Diff line number Diff line change
@@ -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 <vid>``, 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 == []