From 6ac7a6f6a24bb9d0b08c09859f9404db1648690b Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Mon, 2 Nov 2026 08:51:21 +0100 Subject: [PATCH] refactor(dhcp): move the Kea subnet lookup into kea_reservations create_dhcp_reservation and _kea_subnet_uuid_for each walked the searchSubnet rows for the one holding an address. Both now call the pure subnet_containing(), which brings create_dhcp_reservation under the complexity limit and back below its recorded length after #40; the quality baseline records the shrunk entries. --- napalm_opnsense/kea_reservations.py | 16 +++++++++++++ napalm_opnsense/opnsense.py | 35 +++++++++++------------------ tests/quality_baseline.json | 5 ++--- tests/unit/test_kea_reservations.py | 25 ++++++++++++++++++++- 4 files changed, 55 insertions(+), 26 deletions(-) diff --git a/napalm_opnsense/kea_reservations.py b/napalm_opnsense/kea_reservations.py index dc064a4..5ed27ea 100644 --- a/napalm_opnsense/kea_reservations.py +++ b/napalm_opnsense/kea_reservations.py @@ -7,6 +7,7 @@ edited by hand (#26), so every lookup here checks both. from __future__ import annotations +from ipaddress import ip_address, ip_network from typing import Any from napalm_device_types.dhcp import normalize_mac @@ -19,6 +20,21 @@ 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 subnet_containing(rows: list[dict[str, Any]], ip: str) -> dict[str, Any] | None: + """The first ``searchSubnet`` row whose subnet holds *ip*; None when none does. + + A row without a readable ``subnet`` is skipped. + """ + address = ip_address(ip) + for row in rows: + try: + if address in ip_network(str(row["subnet"]).strip(), strict=False): + return row + except (ValueError, KeyError): + continue + return None + + 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*. diff --git a/napalm_opnsense/opnsense.py b/napalm_opnsense/opnsense.py index b421d1b..29977c3 100644 --- a/napalm_opnsense/opnsense.py +++ b/napalm_opnsense/opnsense.py @@ -41,7 +41,6 @@ import logging import re import socket import time -from ipaddress import ip_address, ip_network from typing import Any import requests @@ -64,7 +63,12 @@ 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.kea_reservations import ( + lease_held, + reservation_unchanged, + split_by_mac, + subnet_containing, +) 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 @@ -1462,19 +1466,10 @@ class OPNsenseDriver( except Exception as exc: raise RuntimeError(f"Kea DHCPv4 plugin unavailable: {exc}") from exc - ip_obj = ip_address(ip) - subnet_uuid = None - subnet_cidr = "" - for row in subnets: - try: - if ip_obj in ip_network(row["subnet"], strict=False): - subnet_uuid = row["uuid"] - subnet_cidr = str(row["subnet"]).strip() - break - except ValueError: - continue - if subnet_uuid is None: + subnet_row = subnet_containing(subnets, ip) + if subnet_row is None: raise ValueError(f"No Kea-managed subnet contains {ip}") + subnet_uuid, subnet_cidr = subnet_row["uuid"], str(subnet_row["subnet"]).strip() existing_row = self._kea_own_reservation(ip, mac) @@ -1632,14 +1627,10 @@ class OPNsenseDriver( return str(row["uuid"]) raise ValueError(f"No Kea-managed subnet matches {subnet}") - ip_obj = ip_address(ip) - for row in rows: - try: - if ip_obj in ip_network(row["subnet"], strict=False): - return str(row["uuid"]) - except (ValueError, KeyError): - continue - raise ValueError(f"No Kea-managed subnet contains {ip}") + row = subnet_containing(rows, ip) + if row is None: + raise ValueError(f"No Kea-managed subnet contains {ip}") + return str(row["uuid"]) def get_dhcp_reservations(self) -> list[dict[str, Any]]: """Return all Kea DHCPv4 static reservations, vendor-neutral. diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index a0c1215..4edd572 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -10,7 +10,6 @@ "napalm_opnsense/opnsense.py::OPNsenseDriver._kea_read_list": 11, "napalm_opnsense/opnsense.py::OPNsenseDriver.apply_dhcp_subnet": 21, "napalm_opnsense/opnsense.py::OPNsenseDriver.apply_firewall_rule": 11, - "napalm_opnsense/opnsense.py::OPNsenseDriver.create_dhcp_reservation": 12, "napalm_opnsense/opnsense.py::OPNsenseDriver.delete_dhcp_reservation_and_lease": 11, "napalm_opnsense/opnsense.py::OPNsenseDriver.get_bgp_neighbors": 16, "napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases": 15, @@ -33,7 +32,7 @@ "function_lines": { "napalm_opnsense/opnsense.py::OPNsenseDriver._regenerate_web_cert": 51, "napalm_opnsense/opnsense.py::OPNsenseDriver.apply_dhcp_subnet": 60, - "napalm_opnsense/opnsense.py::OPNsenseDriver.create_dhcp_reservation": 72, + "napalm_opnsense/opnsense.py::OPNsenseDriver.create_dhcp_reservation": 64, "napalm_opnsense/opnsense.py::OPNsenseDriver.delete_dhcp_reservation_and_lease": 79, "napalm_opnsense/opnsense.py::OPNsenseDriver.get_bgp_neighbors": 86, "napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases": 106, @@ -56,7 +55,7 @@ "napalm_opnsense.resolver_mixin" ], "python_file_lines": { - "napalm_opnsense/opnsense.py": 3064 + "napalm_opnsense/opnsense.py": 3058 }, "untyped_public": [ "napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config" diff --git a/tests/unit/test_kea_reservations.py b/tests/unit/test_kea_reservations.py index ffbc24e..fd22d97 100644 --- a/tests/unit/test_kea_reservations.py +++ b/tests/unit/test_kea_reservations.py @@ -1,6 +1,11 @@ """Matching Kea reservations and leases on address and MAC (#26).""" -from napalm_opnsense.kea_reservations import lease_held, reservation_unchanged, split_by_mac +from napalm_opnsense.kea_reservations import ( + lease_held, + reservation_unchanged, + split_by_mac, + subnet_containing, +) def _row(mac, uuid="u-1"): @@ -65,3 +70,21 @@ class TestReservationUnchanged: def test_the_same_reservation_is_unchanged(self): row = dict(self.WANTED, hw_address="02-AA-BB-CC-DD-EE", subnet="172.22.8.0/24") assert reservation_unchanged(row, self.WANTED, "172.22.8.0/24") is True + + +class TestSubnetContaining: + ROWS = [ + {"uuid": "s-broken", "subnet": "not-a-cidr"}, + {"uuid": "s-nocidr"}, + {"uuid": "s-8", "subnet": " 172.22.8.0/24 "}, + {"uuid": "s-wide", "subnet": "172.22.0.0/16"}, + ] + + def test_first_subnet_holding_the_address_wins(self): + assert subnet_containing(self.ROWS, "172.22.8.253") == self.ROWS[2] + + def test_rows_without_a_readable_subnet_are_skipped(self): + assert subnet_containing(self.ROWS, "172.22.9.1") == self.ROWS[3] + + def test_none_when_no_subnet_holds_the_address(self): + assert subnet_containing(self.ROWS, "10.99.99.99") is None