fix(dhcp): release an address before another reservation takes it
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m3s
driver / test (3.12) (pull_request) Successful in 1m25s
driver / test (3.13) (pull_request) Successful in 1m13s
driver / lowest (pull_request) Successful in 45s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m10s
CI / driver (pull_request) Successful in 3m6s
driver / publish (pull_request) Skipped

apply_dhcp_reservationset wrote adds first, then updates in the order of
the desired set. Kea keeps addresses unique at each write, so when an
address moved from one reservation to another, the reservation taking it
was refused as a duplicate whenever it came first.

The changes are now ordered (_dhcp_order): an update that moves a
reservation off its address goes before the change that takes that
address, along a chain from its free end, and adds come after every
update. A swap or rotation of addresses has no such order; its changes
are still tried, so a server that checks only at the commit takes them,
and a refused one's [failed] line says it was a swap and with which
reservations. Nothing is moved to a temporary address: the contract
knows no free one, and a failed second write would leave it there.

The diff is computed against one read of the reservations, shared with
diff_dhcp_reservations. Refused rows still do not stop the others, the
rest is committed and DhcpApplyError follows, as since 4.35.1.

Closes #106
This commit is contained in:
christianmanivong committed 2026-11-12 19:07:31 +01:00
1 parent 5258a43dc9
commit b4cdcfd347
7 files changed
+347 -43

No files matched your search

-1
View File
@@ -20,7 +20,6 @@
},
"function_lines": {
"napalm_device_types/_ucd_metrics.py::collect_ucd_metrics": 119,
"napalm_device_types/dhcp.py::DhcpServerMixin.diff_dhcp_reservations": 54,
"napalm_device_types/dhcp.py::DhcpServerMixin.diff_dhcp_subnets": 60,
"napalm_device_types/firewall_rules.py::FirewallRuleMixin.diff_firewall_rules": 56,
"napalm_device_types/hypervisor.py::HypervisorDriver.create_vm_from_cloud_init": 84,
+150
View File
@@ -298,6 +298,156 @@ class TestApplyWithARefusedReservation:
assert issubclass(DhcpApplyError, RuntimeError)
#: What Kea answers through OPNsense's API for an address another reservation holds.
_KEA_DUPLICATE = (
"{'result': 'failed', 'validations': {'reservation.ip_address': 'Duplicate entry exists.'}}"
)
class _KeaLikeServer(_FakeDhcpServer):
"""A server that keeps each address unique at every write, as Kea does: a write
taking an address another reservation still holds is refused."""
def apply_dhcp_reservation(
self, reservation: DhcpReservationDict, *, uuid: str | None = None
) -> dict[str, Any]:
if any(r["ip"] == reservation["ip"] and r["uuid"] != uuid for r in self.live):
raise RuntimeError(_KEA_DUPLICATE)
stored = {**reservation, "uuid": uuid or f"new-{len(self.live)}"}
self.live = [r for r in self.live if r["uuid"] != uuid] + [stored] # type: ignore[list-item]
return super().apply_dhcp_reservation(reservation, uuid=uuid)
def ip_of(self, mac: str) -> str:
return next(r["ip"] for r in self.live if r["mac"] == mac)
_A, _B, _C, _N = (f"02:00:00:00:00:0{i}" for i in "abcd")
def _at(mac: str, ip: str, uuid: str = "") -> DhcpReservationDict:
return _reservation(mac=mac, ip=ip, uuid=uuid, subnet="192.0.2.0/24")
class TestApplyOrderReleasesBeforeTaking:
"""An address is released before another change takes it (#106)."""
def test_an_update_that_frees_an_address_goes_first(self):
# The issue: B takes A's address, A moves on; desired lists B first.
driver = _KeaLikeServer([_at(_A, "192.0.2.10", "ua"), _at(_B, "192.0.2.11", "ub")])
lines = list(
driver.apply_dhcp_reservationset([_at(_B, "192.0.2.10"), _at(_A, "192.0.2.20")])
)
assert driver.ip_of(_A) == "192.0.2.20"
assert driver.ip_of(_B) == "192.0.2.10"
assert lines == [
f"[update] {_A} -> 192.0.2.20 (ip)",
f"[update] {_B} -> 192.0.2.10 (ip)",
"[commit] applied 0 add(s), 2 update(s)",
]
def test_a_chain_is_written_from_its_free_end(self):
live = [
_at(_A, "192.0.2.10", "ua"),
_at(_B, "192.0.2.11", "ub"),
_at(_C, "192.0.2.12", "uc"),
]
driver = _KeaLikeServer(live)
list(
driver.apply_dhcp_reservationset(
[_at(_A, "192.0.2.11"), _at(_B, "192.0.2.12"), _at(_C, "192.0.2.13")]
)
)
assert [e["reservation"]["mac"] for e in driver.applied] == [_C, _B, _A]
assert [driver.ip_of(m) for m in (_A, _B, _C)] == ["192.0.2.11", "192.0.2.12", "192.0.2.13"]
def test_an_add_comes_after_the_update_that_frees_its_address(self):
driver = _KeaLikeServer([_at(_A, "192.0.2.10", "ua")])
lines = list(
driver.apply_dhcp_reservationset([_at(_N, "192.0.2.10"), _at(_A, "192.0.2.20")])
)
assert driver.ip_of(_N) == "192.0.2.10"
assert driver.ip_of(_A) == "192.0.2.20"
assert lines[-1] == "[commit] applied 1 add(s), 1 update(s)"
def test_addresses_match_however_they_are_spelled(self):
driver = _FakeDhcpServer([_at(_A, "2001:DB8::10", "ua"), _at(_B, "2001:DB8::11", "ub")])
list(driver.apply_dhcp_reservationset([_at(_B, "2001:db8::10"), _at(_A, "2001:db8::20")]))
assert [e["reservation"]["mac"] for e in driver.applied] == [_A, _B]
def test_an_update_that_keeps_its_address_frees_nothing(self):
# A hostname change is no release: the add for A's address stays refused.
driver = _KeaLikeServer([_at(_A, "192.0.2.10", "ua")])
with pytest.raises(DhcpApplyError, match="1 of 2"):
list(
driver.apply_dhcp_reservationset(
[_at(_N, "192.0.2.10"), {**_at(_A, "192.0.2.10"), "hostname": "renamed"}]
)
)
assert driver.ip_of(_A) == "192.0.2.10"
class TestApplyOrderWithASwap:
"""Two reservations trading addresses: no order frees one first. Each is still
tried -- a server that checks only at the commit takes them -- and a refusal says it
was a swap. Nothing is moved to a temporary address: the contract has no way to know
a free one, and a second write that failed would leave the reservation there."""
def _swap(self) -> list[DhcpReservationDict]:
return [_at(_A, "192.0.2.11"), _at(_B, "192.0.2.10"), _at(_N, "192.0.2.30")]
def _live(self) -> list[DhcpReservationDict]:
return [_at(_A, "192.0.2.10", "ua"), _at(_B, "192.0.2.11", "ub")]
def test_a_refused_swap_is_reported_as_one_and_the_rest_is_written(self):
driver = _KeaLikeServer(self._live())
lines: list[str] = []
with pytest.raises(DhcpApplyError, match="2 of 3"):
for line in driver.apply_dhcp_reservationset(self._swap()):
lines.append(line)
failed = [line for line in lines if line.startswith("[failed]")]
assert len(failed) == 2
assert all("Duplicate entry exists" in line for line in failed)
assert f"swap with {_B}" in failed[0] and f"swap with {_A}" in failed[1]
assert driver.ip_of(_A) == "192.0.2.10" and driver.ip_of(_B) == "192.0.2.11"
assert driver.ip_of(_N) == "192.0.2.30"
assert driver.commits == 1
def test_a_server_that_takes_the_swap_gets_it(self):
driver = _FakeDhcpServer(self._live())
lines = list(driver.apply_dhcp_reservationset(self._swap()))
assert len(driver.applied) == 3
assert not any("swap" in line for line in lines)
def test_a_rotation_of_three_is_a_swap_too(self):
driver = _KeaLikeServer([*self._live(), _at(_C, "192.0.2.12", "uc")])
lines: list[str] = []
with pytest.raises(DhcpApplyError, match="3 of 3"):
for line in driver.apply_dhcp_reservationset(
[_at(_A, "192.0.2.11"), _at(_B, "192.0.2.12"), _at(_C, "192.0.2.10")]
):
lines.append(line)
by_mac = {line.split()[1]: line for line in lines if line.startswith("[failed]")}
assert f"swap with {_B}, {_C}" in by_mac[_A]
assert f"swap with {_A}, {_C}" in by_mac[_B]
assert f"swap with {_A}, {_B}" in by_mac[_C]
class TestKeysThatCannotNameOneReservation:
def test_a_live_reservation_without_mac_is_never_matched(self):
driver = _FakeDhcpServer([_reservation(uuid="b", mac="")])