fix(dhcp): match Kea reservations on address and MAC
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 1m16s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Successful in 2m45s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 1m16s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Successful in 2m45s
driver / publish (pull_request) Skipped
create_dhcp_reservation and delete_dhcp_reservation_and_lease looked a reservation up by its address alone. A reservation another MAC held for the address, made by hand or left from an earlier host, was overwritten on create and removed on delete, together with that host's lease. Create now raises instead of taking it over, and delete leaves another MAC's reservation and lease in place and names that MAC in the new reservation_other_mac field. The matching lives in kea_reservations, a module under strict typing. Closes #26
This commit is contained in:
1 parent
4fc7b2424e
commit
ea0a52717e
6 files changed
+260
-64
No files matched your search
+36
-49
@@ -64,6 +64,7 @@ from requests.exceptions import RequestException
|
||||
|
||||
from napalm_opnsense.api_endpoint import ALIVE_TIMEOUT, api_endpoint
|
||||
from napalm_opnsense.ha import config_sync, dhcp_ha
|
||||
from napalm_opnsense.kea_reservations import lease_held, reservation_unchanged, split_by_mac
|
||||
from napalm_opnsense.listening import parse_socket_statistics, wireguard_listen_ports
|
||||
from napalm_opnsense.ospf_mixin import OPNsenseOspfMixin
|
||||
from napalm_opnsense.ping_mixin import OPNsensePingMixin
|
||||
@@ -1452,7 +1453,8 @@ class OPNsenseDriver(
|
||||
:param hostname: optional hostname to record on the reservation.
|
||||
:raises ValueError: if no Kea subnet contains ``ip``.
|
||||
:raises RuntimeError: if Kea rejects the reservation (validation
|
||||
errors) or the Kea plugin isn't installed/enabled.
|
||||
errors), the Kea plugin isn't installed/enabled, or ``ip`` is
|
||||
already reserved for another MAC (left untouched; the caller decides).
|
||||
"""
|
||||
try:
|
||||
subnets = self._get("/api/kea/dhcpv4/searchSubnet").get("rows") or []
|
||||
@@ -1473,21 +1475,7 @@ class OPNsenseDriver(
|
||||
if subnet_uuid is None:
|
||||
raise ValueError(f"No Kea-managed subnet contains {ip}")
|
||||
|
||||
# Idempotency: reuse an existing reservation for this IP if one
|
||||
# already exists (e.g. a retried provisioning job), rather than
|
||||
# creating a duplicate Kea rejects anyway.
|
||||
existing_row: dict[str, Any] | None = None
|
||||
try:
|
||||
existing = self._post(
|
||||
"/api/kea/dhcpv4/searchReservation",
|
||||
{"current": 1, "rowCount": -1, "searchPhrase": ip},
|
||||
)
|
||||
for row in existing.get("rows") or []:
|
||||
if row.get("ip_address") == ip:
|
||||
existing_row = row
|
||||
break
|
||||
except Exception as exc:
|
||||
logger.debug("Kea reservation search failed, proceeding to add: %s", exc)
|
||||
existing_row = self._kea_own_reservation(ip, mac)
|
||||
|
||||
payload = {
|
||||
"reservation": {
|
||||
@@ -1498,7 +1486,7 @@ class OPNsenseDriver(
|
||||
"description": self._NETORK_TAG,
|
||||
}
|
||||
}
|
||||
if existing_row is not None and self._kea_reservation_unchanged(
|
||||
if existing_row is not None and reservation_unchanged(
|
||||
existing_row, payload["reservation"], subnet_cidr
|
||||
):
|
||||
logger.debug("Kea reservation for %s is already as requested, not touched", ip)
|
||||
@@ -1516,26 +1504,25 @@ class OPNsenseDriver(
|
||||
|
||||
self._post("/api/kea/service/reconfigure")
|
||||
|
||||
@staticmethod
|
||||
def _kea_reservation_unchanged(
|
||||
row: dict[str, Any], wanted: dict[str, Any], subnet_cidr: str
|
||||
) -> bool:
|
||||
"""Whether a ``searchReservation`` row already holds every field we would write.
|
||||
|
||||
The MAC is compared normalised: Kea keeps it as it was entered, in
|
||||
either case and with ``:`` or ``-``. The subnet is a model relation that
|
||||
comes back as the subnet's CIDR or its UUID depending on the OPNsense
|
||||
version, so either counts. A field the row does not carry counts as a
|
||||
difference -- writing once too often is the safe side.
|
||||
"""
|
||||
if str(row.get("subnet") or "").strip() not in {wanted["subnet"], subnet_cidr}:
|
||||
return False
|
||||
if normalize_mac(row.get("hw_address")) != normalize_mac(wanted["hw_address"]):
|
||||
return False
|
||||
return all(
|
||||
str(row.get(field) or "") == str(wanted[field] or "")
|
||||
for field in ("ip_address", "hostname", "description")
|
||||
def _kea_reservations_at(self, ip: str) -> list[dict[str, Any]]:
|
||||
"""The ``searchReservation`` rows for *ip* -- the search is a phrase match."""
|
||||
found = self._post(
|
||||
"/api/kea/dhcpv4/searchReservation",
|
||||
{"current": 1, "rowCount": -1, "searchPhrase": ip},
|
||||
)
|
||||
return [row for row in found.get("rows") or [] if row.get("ip_address") == ip]
|
||||
|
||||
def _kea_own_reservation(self, ip: str, mac: str) -> dict[str, Any] | None:
|
||||
"""*mac*'s reservation for *ip*, updated in place on a retry; raises if another
|
||||
MAC holds *ip* (#26)."""
|
||||
try:
|
||||
own, other = split_by_mac(self._kea_reservations_at(ip), mac)
|
||||
except Exception as exc:
|
||||
logger.debug("Kea reservation search failed, proceeding to add: %s", exc)
|
||||
return None
|
||||
if own is None and other:
|
||||
raise RuntimeError(f"Kea already reserves {ip} for {other}, not {normalize_mac(mac)}")
|
||||
return own
|
||||
|
||||
def delete_dhcp_reservation_and_lease(self, mac: str, ip: str) -> dict[str, Any]:
|
||||
"""Remove a Kea DHCPv4 static reservation and any active lease for (mac, ip).
|
||||
@@ -1565,10 +1552,14 @@ class OPNsenseDriver(
|
||||
returns ``{"status": "error", "message": "Missing lease IP
|
||||
parameter"}``; only ``POST /api/kea/leases4/del_lease/{ip}`` works.
|
||||
|
||||
Both match on ``ip`` and ``mac``: another MAC's (an address reused or
|
||||
edited by hand) is left alone, its reservation reported (#26).
|
||||
|
||||
:param mac: NIC MAC address of the reservation to remove.
|
||||
:param ip: IP address of the reservation/lease to remove.
|
||||
:returns: {"reservation_found", "reservation_deleted", "lease_found",
|
||||
"lease_deleted"} — all bool.
|
||||
"lease_deleted"} — all bool — and ``reservation_other_mac``, the MAC
|
||||
another host holds a reservation for ``ip`` under ("" if none).
|
||||
:raises RuntimeError: Kea plugin unavailable, or Kea rejects
|
||||
deletion of a reservation that does exist.
|
||||
"""
|
||||
@@ -1577,26 +1568,22 @@ class OPNsenseDriver(
|
||||
"reservation_deleted": False,
|
||||
"lease_found": False,
|
||||
"lease_deleted": False,
|
||||
"reservation_other_mac": "",
|
||||
}
|
||||
|
||||
# --- Reservation ---
|
||||
try:
|
||||
existing = self._post(
|
||||
"/api/kea/dhcpv4/searchReservation",
|
||||
{"current": 1, "rowCount": -1, "searchPhrase": ip},
|
||||
)
|
||||
rows = self._kea_reservations_at(ip)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"Kea DHCPv4 plugin unavailable: {exc}") from exc
|
||||
|
||||
reservation_uuid = None
|
||||
for row in existing.get("rows") or []:
|
||||
if row.get("ip_address") == ip:
|
||||
reservation_uuid = row.get("uuid")
|
||||
break
|
||||
own, result["reservation_other_mac"] = split_by_mac(rows, mac)
|
||||
if result["reservation_other_mac"]:
|
||||
logger.warning("Kea reservation of another MAC for %s left alone", ip)
|
||||
|
||||
if reservation_uuid:
|
||||
if own and own.get("uuid"):
|
||||
result["reservation_found"] = True
|
||||
del_result = self._post(f"/api/kea/dhcpv4/delReservation/{reservation_uuid}")
|
||||
del_result = self._post(f"/api/kea/dhcpv4/delReservation/{own['uuid']}")
|
||||
if del_result.get("result") != "deleted":
|
||||
raise RuntimeError(f"Kea rejected reservation delete for {ip}: {del_result}")
|
||||
result["reservation_deleted"] = True
|
||||
@@ -1606,7 +1593,7 @@ class OPNsenseDriver(
|
||||
try:
|
||||
leases = self._get("/api/kea/leases4/search")
|
||||
rows = leases.get("rows") or leases.get("leases") or []
|
||||
if any((row.get("address") or row.get("ip-address")) == ip for row in rows):
|
||||
if lease_held(rows, ip, mac):
|
||||
result["lease_found"] = True
|
||||
del_lease = self._post(f"/api/kea/leases4/del_lease/{ip}")
|
||||
result["lease_deleted"] = bool(
|
||||
|
||||
Reference in new issue
Block a user