"""Which Kea DHCPv4 reservation or lease is whose, read from the os-kea API rows. A reservation is the pair of an address and a MAC. Matching on the address alone takes over or removes another host's reservation once an address was reused or edited by hand (#26), so every lookup here checks both. """ from __future__ import annotations from typing import Any from napalm_device_types.dhcp import normalize_mac #: Where a ``leases4/search`` row keeps the client's MAC: os-kea, then plain Kea. _LEASE_MAC_FIELDS = ("hwaddr", "hw-address") def _mac_of(row: dict[str, Any], *fields: str) -> str: return normalize_mac(next((str(row[f]) for f in fields if row.get(f)), "")) def split_by_mac(rows: list[dict[str, Any]], mac: str) -> tuple[dict[str, Any] | None, str]: """``(the row *mac* holds, the MAC of a row another host holds)`` among *rows*. *rows* are ``searchReservation`` rows for one address; either part is ``None`` or ``""`` when there is none. """ wanted = normalize_mac(mac) own = next((row for row in rows if _mac_of(row, "hw_address") == wanted), None) others = [_mac_of(row, "hw_address") for row in rows] return own, next((m for m in others if m and m != wanted), "") def lease_held(rows: list[dict[str, Any]], ip: str, mac: str) -> bool: """Whether a ``leases4/search`` row gives *ip* to *mac*.""" return any( (row.get("address") or row.get("ip-address")) == ip and _mac_of(row, *_LEASE_MAC_FIELDS) == normalize_mac(mac) for row in rows ) def 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") )