From 6eab86f29579b362a779f265f6db54e16c9af202 Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Wed, 7 Oct 2026 01:14:01 +0000 Subject: [PATCH 1/9] [dhcpservd][dhcp_server] Phase 3: compile MATCH bindings into Kea config Teach dhcp_cfggen to translate DHCP_SERVER_IPV4_MATCH and DHCP_SERVER_IPV4_BINDING into Kea client-classes and class-scoped pools: * circuit_id resolves the port alias to : and compiles to relay4[1].hex; option60 compiles to option[60].hex. Both are hex encoded and length checked against the 255 byte option limit. * Conditions within a binding are ANDed. Specificity ordering is made order independent by subtracting the predicates of every more specific overlapping binding from each less specific one, rather than relying on Kea class evaluation order. * Bindings that share an identical pool are coalesced into a single client-class with ORed predicates, so Kea never sees two pools with the same address range. Partially overlapping pools and equal specificity overlaps are rejected at generation time. * Class names are deterministic, so an unchanged Config DB renders a byte identical Kea config and avoids needless reloads. MATCH mode becomes selectable in this commit rather than earlier, so the enum, the CLI that sets it and the code that consumes it all land together: * DHCP_SERVER_IPV4.mode gains the MATCH value in the YANG model, and the model fixtures move to mode MATCH accordingly. * config dhcp_server ipv4 add|update --mode now accepts MATCH, and enable/update refuse to activate MATCH mode on a VLAN that has no binding, since that would render an interface with no pool. Exposing the mode before this point would have let dhcprelayd redirect the relay to a local Kea that renders no subnet for the interface, silently dropping every request: dhcprelayd keys only on the interface state, never on its mode, and the generator emitted subnets for PORT mode alone. dhcpservd validates each candidate config with kea-dhcp4 -t before activating it and keeps the last known good config when generation fails. Table subscriptions follow the per interface mode. Refs: sonic-net/SONiC#2535 Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 56 +++ .../cli/config/plugins/dhcp_server.py | 19 +- .../dhcp_utilities/common/dhcp_db_monitor.py | 56 ++- .../dhcp_utilities/dhcpservd/dhcp_cfggen.py | 424 ++++++++++++++++- .../dhcp_utilities/dhcpservd/dhcpservd.py | 132 +++++- .../tests/test_dhcp_cfggen.py | 15 +- .../tests/test_dhcp_db_monitor.py | 50 +- .../tests/test_dhcp_match_cfggen.py | 435 ++++++++++++++++++ .../tests/test_dhcpservd.py | 211 +++++++-- .../tests/test_smart_switch.py | 7 +- src/sonic-yang-models/doc/Configuration.md | 8 - .../tests/dhcp_server_ipv4_match.json | 4 +- .../tests_config/dhcp_server_ipv4_match.json | 40 +- .../yang-models/sonic-dhcp-server-ipv4.yang | 1 + 14 files changed, 1364 insertions(+), 94 deletions(-) create mode 100644 src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index d088931d645..f5dbf165c37 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -28,6 +28,62 @@ def dhcp_vlan200(mock_db): class TestConfigDHCPServerMatch: + def test_add_interface_in_match_mode(self, mock_db): + result = invoke( + mock_db, + IPV4_COMMAND.commands["add"], + [ + "Vlan200", + "--mode=MATCH", + "--lease_time=1000", + "--gateway=100.1.2.2", + "--netmask=255.255.255.0", + ], + ) + + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan200", "mode") == "MATCH" + + def test_update_disabled_interface_to_match_mode(self, mock_db): + result = invoke(mock_db, IPV4_COMMAND.commands["update"], ["Vlan300", "--mode=MATCH"]) + + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan300", "mode") == "MATCH" + + def test_update_enabled_interface_to_match_mode(self, mock_db): + result = invoke(mock_db, IPV4_COMMAND.commands["update"], ["Vlan100", "--mode=MATCH"]) + + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode") == "MATCH" + + def test_update_enabled_interface_to_match_mode_without_binding(self, mock_db): + mock_db.delete("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-a") + mock_db.delete("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|fallback") + + result = invoke(mock_db, IPV4_COMMAND.commands["update"], ["Vlan100", "--mode=MATCH"]) + + assert result.exit_code == 2 + assert "requires at least one binding" in result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode") == "PORT" + + def test_enable_match_interface_with_valid_bindings(self, mock_db): + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state", "disabled") + + result = invoke(mock_db, IPV4_COMMAND.commands["enable"], ["Vlan100"]) + + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state") == "enabled" + + def test_enable_match_interface_without_binding(self, mock_db): + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan300", "mode", "MATCH") + + result = invoke(mock_db, IPV4_COMMAND.commands["enable"], ["Vlan300"]) + + assert result.exit_code == 2 + assert "requires at least one binding" in result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan300", "state") == "disabled" + def test_delete_interface_referenced_by_match_binding(self, mock_db): for key in list(mock_db.keys("CONFIG_DB", "DHCP_SERVER_IPV4_PORT|Vlan100|*")): mock_db.delete("CONFIG_DB", key) diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 5f275986105..46a58eb9a24 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -7,6 +7,7 @@ SUPPORTED_TYPE = ["binary", "boolean", "ipv4-address", "string", "uint8", "uint16", "uint32"] +SUPPORTED_MODE = ["PORT", "MATCH"] SUPPORTED_MATCH_TYPE = ["circuit_id", "option60"] @@ -217,7 +218,7 @@ def predicates_overlap(first, second): def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrides=None, - range_overrides=None, port_alias_map=None): + range_overrides=None, port_alias_map=None, require_binding=False): bindings = {} prefix = "DHCP_SERVER_IPV4_BINDING|{}|".format(dhcp_interface) for key in dbconn.keys("CONFIG_DB", prefix + "*"): @@ -226,6 +227,9 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid bindings[candidate[0]] = candidate[1] if port_alias_map is None: port_alias_map = {} + if require_binding and not bindings: + click.get_current_context().fail("MATCH mode requires at least one binding on {}".format(dhcp_interface)) + predicates = {} for binding_name in sorted(bindings): predicates[binding_name] = validate_binding_entry( @@ -288,6 +292,7 @@ def validate_match_update(dbconn, match_name, updated_entry, port_alias_map=None dhcp_interface, match_overrides={match_name: updated_entry}, port_alias_map=port_alias_map, + require_binding=True, ) @@ -320,8 +325,8 @@ def dhcp_server_ipv4(): @clicommon.pass_db def dhcp_server_ipv4_add(db, mode, lease_time, dup_gw_nm, gateway, netmask, dhcp_interface): ctx = click.get_current_context() - if mode != "PORT": - ctx.fail("Only mode PORT is supported") + if mode not in SUPPORTED_MODE: + ctx.fail("Only modes {} are supported".format(", ".join(SUPPORTED_MODE))) if not validate_str_type("uint32", lease_time): ctx.fail("lease_time is required and must be nonnegative integer") dbconn = db.db @@ -385,8 +390,10 @@ def dhcp_server_ipv4_update(db, mode, lease_time, dup_gw_nm, gateway, netmask, d ctx.fail("Dhcp interface {} does not exist in config db".format(dhcp_interface)) updates = {} if mode: - if mode != "PORT": - ctx.fail("Only mode PORT is supported") + if mode not in SUPPORTED_MODE: + ctx.fail("Only modes {} are supported".format(", ".join(SUPPORTED_MODE))) + if mode == "MATCH" and dbconn.get("CONFIG_DB", interface_key, "state") == "enabled": + validate_vlan_bindings(dbconn, dhcp_interface, require_binding=True) updates["mode"] = mode if lease_time: if not validate_str_type("uint32", lease_time): @@ -422,6 +429,8 @@ def dhcp_server_ipv4_enable(db, dhcp_interface): dbconn = db.db key = "DHCP_SERVER_IPV4|" + dhcp_interface if dbconn.exists("CONFIG_DB", key): + if dbconn.get("CONFIG_DB", key, "mode") == "MATCH": + validate_vlan_bindings(dbconn, dhcp_interface, require_binding=True) dbconn.set("CONFIG_DB", key, "state", "enabled") else: ctx.fail("Failed to enable, dhcp interface {} does not exist".format(dhcp_interface)) diff --git a/src/sonic-dhcp-utilities/dhcp_utilities/common/dhcp_db_monitor.py b/src/sonic-dhcp-utilities/dhcp_utilities/common/dhcp_db_monitor.py index cbc46cfee47..9616cb11daa 100644 --- a/src/sonic-dhcp-utilities/dhcp_utilities/common/dhcp_db_monitor.py +++ b/src/sonic-dhcp-utilities/dhcp_utilities/common/dhcp_db_monitor.py @@ -7,6 +7,8 @@ DEFAULT_SELECT_TIMEOUT = 5000 # millisecond DHCP_SERVER_IPV4 = "DHCP_SERVER_IPV4" DHCP_SERVER_IPV4_PORT = "DHCP_SERVER_IPV4_PORT" +DHCP_SERVER_IPV4_MATCH = "DHCP_SERVER_IPV4_MATCH" +DHCP_SERVER_IPV4_BINDING = "DHCP_SERVER_IPV4_BINDING" DHCP_SERVER_IPV4_RANGE = "DHCP_SERVER_IPV4_RANGE" DHCP_SERVER_IPV4_CUSTOMIZED_OPTIONS = "DHCP_SERVER_IPV4_CUSTOMIZED_OPTIONS" VLAN = "VLAN" @@ -225,12 +227,53 @@ def __init__(self, sel, db): ConfigDbEventChecker.__init__(self, sel, db) def _get_parameter(self, db_snapshot): - return ConfigDbEventChecker.get_parameter_by_name(db_snapshot, "enabled_dhcp_interfaces") + return ConfigDbEventChecker.get_parameter_by_name(db_snapshot, "enabled_port_interfaces") - def _process_check(self, key, op, entry, enabled_dhcp_interfaces): + def _process_check(self, key, op, entry, enabled_port_interfaces): dhcp_interface = key.split("|")[0] # If dhcp interface is enabled, need to generate new configuration - if dhcp_interface in enabled_dhcp_interfaces: + if dhcp_interface in enabled_port_interfaces: + self.clear_event() + return True + return False + + +class DhcpMatchTableEventChecker(ConfigDbEventChecker): + """ + This event checker is interested in active DHCP_SERVER_IPV4_MATCH entries. + """ + table_name = DHCP_SERVER_IPV4_MATCH + + def __init__(self, sel, db): + self.table_name = DHCP_SERVER_IPV4_MATCH + ConfigDbEventChecker.__init__(self, sel, db) + + def _get_parameter(self, db_snapshot): + return ConfigDbEventChecker.get_parameter_by_name(db_snapshot, "used_matches") + + def _process_check(self, key, op, entry, used_matches): + if key in used_matches: + self.clear_event() + return True + return False + + +class DhcpBindingTableEventChecker(ConfigDbEventChecker): + """ + This event checker is interested in bindings on enabled MATCH interfaces. + """ + table_name = DHCP_SERVER_IPV4_BINDING + + def __init__(self, sel, db): + self.table_name = DHCP_SERVER_IPV4_BINDING + ConfigDbEventChecker.__init__(self, sel, db) + + def _get_parameter(self, db_snapshot): + return ConfigDbEventChecker.get_parameter_by_name(db_snapshot, "enabled_match_interfaces") + + def _process_check(self, key, op, entry, enabled_match_interfaces): + dhcp_interface = key.split("|")[0] + if dhcp_interface in enabled_match_interfaces: self.clear_event() return True return False @@ -523,6 +566,13 @@ def check_db_update(self, db_snapshot): state, _ = self.sel.select(self.select_timeout) if state == swsscommon.Select.TIMEOUT or state != swsscommon.Select.OBJECT: return False + if not db_snapshot: + # Recovery mode treats the next event from any subscribed table as + # actionable and drains it before retrying generation. + for checker in self.checker_dict.values(): + if checker.is_enabled(): + checker.clear_event() + return True need_refresh = False for checker in self.checker_dict.values(): if not checker.is_enabled(): diff --git a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py index 4813dc01b59..bdd9c4ad6ed 100755 --- a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py +++ b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +import hashlib import ipaddress import os import syslog @@ -12,6 +13,8 @@ DHCP_SERVER_IPV4_CUSTOMIZED_OPTIONS = "DHCP_SERVER_IPV4_CUSTOMIZED_OPTIONS" DHCP_SERVER_IPV4_RANGE = "DHCP_SERVER_IPV4_RANGE" DHCP_SERVER_IPV4_PORT = "DHCP_SERVER_IPV4_PORT" +DHCP_SERVER_IPV4_MATCH = "DHCP_SERVER_IPV4_MATCH" +DHCP_SERVER_IPV4_BINDING = "DHCP_SERVER_IPV4_BINDING" VLAN_INTERFACE = "VLAN_INTERFACE" VLAN_MEMBER = "VLAN_MEMBER" DPUS = "DPUS" @@ -20,6 +23,9 @@ PORT_MODE_CHECKER = ["DhcpServerTableCfgChangeEventChecker", "DhcpPortTableEventChecker", "DhcpRangeTableEventChecker", "DhcpOptionTableEventChecker", "VlanTableEventChecker", "VlanIntfTableEventChecker", "VlanMemberTableEventChecker"] +MATCH_MODE_CHECKER = ["DhcpServerTableCfgChangeEventChecker", "DhcpMatchTableEventChecker", + "DhcpBindingTableEventChecker", "DhcpRangeTableEventChecker", "DhcpOptionTableEventChecker", + "VlanTableEventChecker", "VlanIntfTableEventChecker", "VlanMemberTableEventChecker"] SMART_SWITCH_CHECKER = ["DpusTableEventChecker", "MidPlaneTableEventChecker"] LEASE_UPDATE_SCRIPT_PATH = "/etc/kea/lease_update.sh" DEFAULT_LEASE_TIME = 900 @@ -29,6 +35,8 @@ DHCP_OPTION_FILE = f"{SCRIPT_DIR}/dhcp_option.csv" SUPPORT_DHCP_OPTION_TYPE = ["binary", "boolean", "ipv4-address", "string", "uint8", "uint16", "uint32"] OPTION_DHCP_SERVER_ID = "54" +SUPPORTED_MATCH_TYPES = ["circuit_id", "option60"] +MAX_DHCP_OPTION_BYTES = 255 class DhcpServCfgGenerator(object): @@ -59,6 +67,9 @@ def generate(self): set of enabled dhcp interface set of used options set of db table need to be monitored + set of enabled PORT-mode interfaces + set of enabled MATCH-mode interfaces + set of match conditions used by enabled MATCH bindings """ # Generate from running config_db # Get host name @@ -75,7 +86,8 @@ def generate(self): mid_plane_table = self.db_connector.get_config_db_table(MID_PLANE_BRIDGE) mid_plane, dpus = self._parse_dpu(dpus_table, mid_plane_table) if smart_switch else ({}, {}) - dhcp_server_ipv4, customized_options_ipv4, range_ipv4, port_ipv4 = self._get_dhcp_ipv4_tables_from_db() + dhcp_server_ipv4, customized_options_ipv4, range_ipv4, port_ipv4, match_ipv4, binding_ipv4 = \ + self._get_dhcp_ipv4_tables_from_db() # Parse range table ranges = self._parse_range(range_ipv4) @@ -89,15 +101,49 @@ def generate(self): }] dpus = ["{}|{}".format(mid_plane_name, dpu) for dpu in dpus] dhcp_members = vlan_members | set(dpus) - port_ips, used_ranges = self._parse_port(port_ipv4, dhcp_interfaces, dhcp_members, ranges) + port_ips, port_used_ranges = self._parse_port(port_ipv4, dhcp_interfaces, dhcp_members, ranges) + match_pools, match_client_classes, match_used_ranges, used_matches = self._parse_match_bindings( + dhcp_server_ipv4, + match_ipv4, + binding_ipv4, + dhcp_interfaces, + vlan_members, + ranges, + hostname + ) customized_options = self._parse_customized_options(customized_options_ipv4) render_obj, enabled_dhcp_interfaces, used_options, subscribe_table = \ - self._construct_obj_for_template(dhcp_server_ipv4, port_ips, hostname, customized_options, smart_switch) + self._construct_obj_for_template( + dhcp_server_ipv4, + port_ips, + hostname, + customized_options, + smart_switch, + match_pools, + match_client_classes + ) + enabled_port_interfaces = { + name for name, config in dhcp_server_ipv4.items() + if config.get("state") == "enabled" and config.get("mode") == "PORT" + } + enabled_match_interfaces = { + name for name, config in dhcp_server_ipv4.items() + if config.get("state") == "enabled" and config.get("mode") == "MATCH" + } if smart_switch: subscribe_table |= set(SMART_SWITCH_CHECKER) - return self._render_config(render_obj), used_ranges, enabled_dhcp_interfaces, used_options, subscribe_table + return ( + self._render_config(render_obj), + port_used_ranges | match_used_ranges, + enabled_dhcp_interfaces, + used_options, + subscribe_table, + enabled_port_interfaces, + enabled_match_interfaces, + used_matches + ) def _parse_dpu(self, dpus_table, mid_plane_table): """ @@ -180,6 +226,7 @@ def _get_render_template(self, kea_conf_template_path): self.kea_template = env.get_template(os.path.basename(kea_conf_template_path)) def _parse_port_map_alias(self): + self.port_alias_map = {} port_table = self.db_connector.get_config_db_table("PORT") pc_table = self.db_connector.get_config_db_table("PORTCHANNEL") for port_name, item in port_table.items(): @@ -187,7 +234,10 @@ def _parse_port_map_alias(self): for pc_name in pc_table.keys(): self.port_alias_map[pc_name] = pc_name - def _construct_obj_for_template(self, dhcp_server_ipv4, port_ips, hostname, customized_options, smart_switch=False): + def _construct_obj_for_template(self, dhcp_server_ipv4, port_ips, hostname, customized_options, smart_switch=False, + match_pools=None, match_client_classes=None): + match_pools = match_pools or {} + match_client_classes = match_client_classes or [] subnets = [] client_classes = [] enabled_dhcp_interfaces = set() @@ -258,6 +308,48 @@ def _construct_obj_for_template(self, dhcp_server_ipv4, port_ips, hostname, cust if "gateway" in dhcp_config: subnet_obj["gateway"] = dhcp_config["gateway"] subnets.append(subnet_obj) + elif dhcp_config["mode"] == "MATCH": + subscribe_table |= set(MATCH_MODE_CHECKER) + if dhcp_interface_name not in match_pools: + raise ValueError("Cannot get DHCP MATCH binding config for {}".format(dhcp_interface_name)) + curr_options = {} + dhcp_server_id_option = {} + if "customized_options" in dhcp_config: + for option in dhcp_config["customized_options"]: + used_options.add(option) + if option not in customized_option_keys: + syslog.syslog(syslog.LOG_WARNING, "Customized option {} configured for {} is not defined" + .format(option, dhcp_interface_name)) + continue + current_option = { + "always_send": customized_options[option]["always_send"], + "value": customized_options[option]["value"], + "option_type": customized_options[option]["option_type"], + "id": customized_options[option]["id"] + } + if customized_options[option]["id"] == OPTION_DHCP_SERVER_ID: + dhcp_server_id_option = current_option + else: + curr_options[option] = current_option + for dhcp_interface_ip, pools in match_pools[dhcp_interface_name].items(): + current_server_id_option = dhcp_server_id_option + if not current_server_id_option: + current_server_id_option = { + "value": dhcp_interface_ip.split("/")[0], + "always_send": "true" + } + subnet_obj = { + "id": MID_PLANE_BRIDGE_SUBNET_ID if smart_switch else dhcp_interface_name.replace("Vlan", ""), + "subnet": str(ipaddress.ip_network(dhcp_interface_ip, strict=False)), + "pools": pools, + "dhcp_server_id_option": current_server_id_option, + "lease_time": dhcp_config["lease_time"] if "lease_time" in dhcp_config else DEFAULT_LEASE_TIME, + "customized_options": curr_options + } + if "gateway" in dhcp_config: + subnet_obj["gateway"] = dhcp_config["gateway"] + subnets.append(subnet_obj) + client_classes.extend(match_client_classes) render_obj = { "subnets": subnets, "client_classes": client_classes, @@ -273,13 +365,15 @@ def _get_dhcp_ipv4_tables_from_db(self): """ Get DHCP Server IPv4 related table from config_db. Returns: - Four table objects. + Six table objects. """ dhcp_server_ipv4 = self.db_connector.get_config_db_table(DHCP_SERVER_IPV4) customized_options_ipv4 = self.db_connector.get_config_db_table(DHCP_SERVER_IPV4_CUSTOMIZED_OPTIONS) range_ipv4 = self.db_connector.get_config_db_table(DHCP_SERVER_IPV4_RANGE) port_ipv4 = self.db_connector.get_config_db_table(DHCP_SERVER_IPV4_PORT) - return dhcp_server_ipv4, customized_options_ipv4, range_ipv4, port_ipv4 + match_ipv4 = self.db_connector.get_config_db_table(DHCP_SERVER_IPV4_MATCH) + binding_ipv4 = self.db_connector.get_config_db_table(DHCP_SERVER_IPV4_BINDING) + return dhcp_server_ipv4, customized_options_ipv4, range_ipv4, port_ipv4, match_ipv4, binding_ipv4 def _get_vlan_ipv4_interface(self, vlan_interface_keys): """ @@ -464,6 +558,322 @@ def _parse_port(self, port_ipv4, dhcp_interfaces, dhcp_members, ranges): port_ips[dhcp_interface_name][dhcp_interface_ip][port_name] = ranges return port_ips, used_ranges + @staticmethod + def _normalize_list(value): + if value is None: + return [] + if isinstance(value, str): + return value.split(",") if value else [] + return list(value) + + @staticmethod + def _merge_match_intervals(intervals): + merged = [] + for start, end in sorted(intervals, key=lambda interval: interval[0]): + if not merged or int(start) > int(merged[-1][1]) + 1: + merged.append([start, end]) + else: + merged[-1][1] = max(merged[-1][1], end) + return merged + + @staticmethod + def _predicates_overlap(first, second): + return all(match_type not in second or second[match_type]["value"] == condition["value"] + for match_type, condition in first.items()) + + @staticmethod + def _interval_sets_overlap(first, second): + for first_start, first_end in first: + for second_start, second_end in second: + if first_start <= second_end and second_start <= first_end: + return True + return False + + def _parse_match_condition(self, match_name, match_ipv4, hostname, condition_cache): + if match_name in condition_cache: + return condition_cache[match_name] + if match_name not in match_ipv4: + raise ValueError("Match {} does not exist".format(match_name)) + + config = match_ipv4[match_name] + match_type = config.get("type") + value = config.get("value") + if match_type not in SUPPORTED_MATCH_TYPES: + raise ValueError("Match {} has unsupported type {}".format(match_name, match_type)) + if not isinstance(value, str) or not value: + raise ValueError("Match {} has an invalid value".format(match_name)) + + port_name = None + resolved_value = value + if match_type == "circuit_id": + ports = sorted(port for port, alias in self.port_alias_map.items() if alias == value) + if not ports: + raise ValueError("Circuit ID value {} does not match any port alias, " + "aliasless port name or PortChannel name".format(value)) + if len(ports) > 1: + raise ValueError("Circuit ID value {} is ambiguous".format(value)) + port_name = ports[0] + resolved_value = "{}:{}".format(hostname, value) + + encoded_value = resolved_value.encode("utf-8") + if len(encoded_value) > MAX_DHCP_OPTION_BYTES: + raise ValueError("Match {} exceeds the DHCP option payload limit".format(match_name)) + if match_type == "circuit_id": + atom = "relay4[1].exists and relay4[1].hex == 0x{}".format(encoded_value.hex()) + else: + atom = "option[60].exists and option[60].hex == 0x{}".format(encoded_value.hex()) + + condition = { + "name": match_name, + "type": match_type, + "value": value, + "port": port_name, + "atom": atom + } + condition_cache[match_name] = condition + return condition + + def _find_match_subnet(self, dhcp_interface_name, dhcp_interfaces, start, end): + if dhcp_interface_name not in dhcp_interfaces: + raise ValueError("Interface {} has no IPv4 subnet".format(dhcp_interface_name)) + matching_subnets = [ + interface for interface in dhcp_interfaces[dhcp_interface_name] + if start in interface["network"] and end in interface["network"] + ] + if not matching_subnets: + raise ValueError( + "Pool {}-{} is not in an IPv4 subnet of {}".format(start, end, dhcp_interface_name) + ) + if len(matching_subnets) > 1: + raise ValueError( + "Pool {}-{} matches multiple IPv4 subnets of {}".format(start, end, dhcp_interface_name) + ) + return matching_subnets[0]["ip"] + + def _parse_binding_pools(self, dhcp_interface_name, binding_name, binding_config, dhcp_interfaces, ranges): + ips = self._normalize_list(binding_config.get("ips")) + range_names = self._normalize_list(binding_config.get("ranges")) + if bool(ips) == bool(range_names): + raise ValueError( + "Binding {}|{} must configure exactly one of ips or ranges".format( + dhcp_interface_name, binding_name + ) + ) + values = ips if ips else range_names + if len(values) != len(set(values)): + raise ValueError("Binding {}|{} contains duplicate pool values".format( + dhcp_interface_name, binding_name + )) + + intervals_by_subnet = {} + used_ranges = set() + if ips: + for ip in values: + try: + address = ipaddress.ip_address(ip) + except ValueError: + raise ValueError("Binding {}|{} contains invalid IP {}".format( + dhcp_interface_name, binding_name, ip + )) + if address.version != 4: + raise ValueError("Binding {}|{} contains non-IPv4 address {}".format( + dhcp_interface_name, binding_name, ip + )) + subnet = self._find_match_subnet( + dhcp_interface_name, dhcp_interfaces, address, address + ) + intervals_by_subnet.setdefault(subnet, []).append([address, address]) + else: + for range_name in values: + used_ranges.add(range_name) + if range_name not in ranges: + raise ValueError("Range {} referenced by {}|{} does not exist".format( + range_name, dhcp_interface_name, binding_name + )) + start, end = ranges[range_name] + subnet = self._find_match_subnet( + dhcp_interface_name, dhcp_interfaces, start, end + ) + intervals_by_subnet.setdefault(subnet, []).append([start, end]) + + for subnet, intervals in intervals_by_subnet.items(): + intervals_by_subnet[subnet] = self._merge_match_intervals(intervals) + return intervals_by_subnet, used_ranges + + def _build_match_class_name(self, dhcp_interface_name, subnet, intervals, binding_keys): + if dhcp_interface_name.startswith("Vlan") and dhcp_interface_name[4:].isdigit(): + interface_id = dhcp_interface_name[4:] + else: + interface_id = hashlib.sha256(dhcp_interface_name.encode("utf-8")).hexdigest()[:8] + interval_text = ",".join("{}-{}".format(start, end) for start, end in intervals) + hash_input = "|".join( + [dhcp_interface_name, subnet, interval_text] + sorted(binding_keys) + ) + suffix = hashlib.sha256(hash_input.encode("utf-8")).hexdigest()[:16] + return "sonic_match_{}_{}".format(interface_id, suffix) + + def _parse_match_bindings(self, dhcp_server_ipv4, match_ipv4, binding_ipv4, dhcp_interfaces, vlan_members, + ranges, hostname): + enabled_match_interfaces = { + name for name, config in dhcp_server_ipv4.items() + if config.get("state") == "enabled" and config.get("mode") == "MATCH" + } + if not enabled_match_interfaces: + return {}, [], set(), set() + + bindings_by_interface = {name: [] for name in enabled_match_interfaces} + for binding_key, binding_config in binding_ipv4.items(): + key_parts = binding_key.split("|", 1) + if len(key_parts) != 2 or key_parts[0] not in enabled_match_interfaces: + continue + bindings_by_interface[key_parts[0]].append((key_parts[1], binding_config)) + + condition_cache = {} + used_matches = set() + used_ranges = set() + compiled_pools = {} + client_classes = [] + + for dhcp_interface_name in sorted(enabled_match_interfaces): + interface_bindings = bindings_by_interface[dhcp_interface_name] + if not interface_bindings: + raise ValueError("MATCH mode requires at least one binding on {}".format(dhcp_interface_name)) + + normalized_bindings = [] + for binding_name, binding_config in sorted(interface_bindings): + match_names = self._normalize_list(binding_config.get("matches")) + if not match_names: + raise ValueError("Binding {}|{} must reference at least one match".format( + dhcp_interface_name, binding_name + )) + if len(match_names) != len(set(match_names)): + raise ValueError("Binding {}|{} contains duplicate matches".format( + dhcp_interface_name, binding_name + )) + + conditions = {} + for match_name in match_names: + condition = self._parse_match_condition( + match_name, match_ipv4, hostname, condition_cache + ) + if condition["type"] in conditions: + raise ValueError( + "Binding {}|{} contains multiple matches of type {}".format( + dhcp_interface_name, binding_name, condition["type"] + ) + ) + if condition["type"] == "circuit_id" and \ + "{}|{}".format(dhcp_interface_name, condition["port"]) not in vlan_members: + raise ValueError( + "Circuit ID value {} is not a member of {}".format( + condition["value"], dhcp_interface_name + ) + ) + conditions[condition["type"]] = condition + used_matches.add(match_name) + + intervals_by_subnet, binding_used_ranges = self._parse_binding_pools( + dhcp_interface_name, + binding_name, + binding_config, + dhcp_interfaces, + ranges + ) + used_ranges |= binding_used_ranges + raw_predicate = " and ".join( + "({})".format(conditions[match_type]["atom"]) + for match_type in SUPPORTED_MATCH_TYPES if match_type in conditions + ) + normalized_bindings.append({ + "name": binding_name, + "key": "{}|{}".format(dhcp_interface_name, binding_name), + "conditions": conditions, + "specificity": len(conditions), + "raw_predicate": raw_predicate, + "intervals_by_subnet": intervals_by_subnet + }) + + for index, first in enumerate(normalized_bindings): + for second in normalized_bindings[index + 1:]: + if first["specificity"] == second["specificity"] and \ + self._predicates_overlap(first["conditions"], second["conditions"]): + raise ValueError( + "Bindings {} and {} overlap with equal specificity".format( + first["key"], second["key"] + ) + ) + common_subnets = set(first["intervals_by_subnet"]) & set(second["intervals_by_subnet"]) + for subnet in common_subnets: + first_intervals = first["intervals_by_subnet"][subnet] + second_intervals = second["intervals_by_subnet"][subnet] + if first_intervals != second_intervals and \ + self._interval_sets_overlap(first_intervals, second_intervals): + raise ValueError( + "Bindings {} and {} have partially overlapping pools".format( + first["key"], second["key"] + ) + ) + + for binding in normalized_bindings: + higher_predicates = sorted( + other["raw_predicate"] for other in normalized_bindings + if other["specificity"] > binding["specificity"] and + self._predicates_overlap(binding["conditions"], other["conditions"]) + ) + effective_predicate = binding["raw_predicate"] + if higher_predicates: + exclusions = " or ".join("({})".format(predicate) for predicate in higher_predicates) + effective_predicate = "({}) and not ({})".format( + binding["raw_predicate"], exclusions + ) + binding["effective_predicate"] = effective_predicate + + pool_groups = {} + for binding in normalized_bindings: + for subnet, intervals in binding["intervals_by_subnet"].items(): + interval_key = tuple((str(start), str(end)) for start, end in intervals) + pool_groups.setdefault((subnet, interval_key), []).append(binding) + + compiled_pools[dhcp_interface_name] = {} + for (subnet, interval_key), grouped_bindings in sorted(pool_groups.items()): + binding_keys = sorted(binding["key"] for binding in grouped_bindings) + class_name = self._build_match_class_name( + dhcp_interface_name, subnet, interval_key, binding_keys + ) + effective_predicates = sorted( + binding["effective_predicate"] for binding in grouped_bindings + ) + class_condition = effective_predicates[0] + if len(effective_predicates) > 1: + class_condition = " or ".join( + "({})".format(predicate) for predicate in effective_predicates + ) + client_classes.append({ + "name": class_name, + "condition": class_condition + }) + syslog.syslog( + syslog.LOG_INFO, + "DHCP MATCH class {} maps to bindings {}".format(class_name, ",".join(binding_keys)) + ) + pools = compiled_pools[dhcp_interface_name].setdefault(subnet, []) + for start, end in interval_key: + pools.append({ + "range": "{} - {}".format(start, end), + "client_class": class_name + }) + + for pools in compiled_pools[dhcp_interface_name].values(): + pools.sort( + key=lambda pool: ( + ipaddress.ip_address(pool["range"].split(" - ")[0]), + pool["client_class"] + ) + ) + + client_classes.sort(key=lambda client_class: client_class["name"]) + return compiled_pools, client_classes, used_ranges, used_matches + def _read_dhcp_option(self, file_path): # TODO current only support unassigned options, use dict in case support more options in the future # key: option code, value: option type list diff --git a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py index caf13e953ff..2c6286a2381 100644 --- a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py +++ b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py @@ -6,16 +6,19 @@ import sys import syslog import os +import tempfile from .dhcp_cfggen import DhcpServCfgGenerator from .dhcp_lease import LeaseManager from dhcp_utilities.common.utils import DhcpDbConnector from dhcp_utilities.common.dhcp_db_monitor import DhcpServdDbMonitor, DhcpServerTableCfgChangeEventChecker, \ DhcpOptionTableEventChecker, DhcpRangeTableEventChecker, DhcpPortTableEventChecker, VlanIntfTableEventChecker, \ - VlanMemberTableEventChecker, VlanTableEventChecker, MidPlaneTableEventChecker, DpusTableEventChecker + VlanMemberTableEventChecker, VlanTableEventChecker, MidPlaneTableEventChecker, DpusTableEventChecker, \ + DhcpMatchTableEventChecker, DhcpBindingTableEventChecker from swsscommon import swsscommon KEA_DHCP4_CONFIG = "/etc/kea/kea-dhcp4.conf" KEA_DHCP4_PROC_NAME = "kea-dhcp4" +KEA_VALIDATION_TIMEOUT = 30 KEA_LEASE_FILE_PATH = "/var/lib/kea/kea-lease.csv" DHCPSERVD_READY_FLAG = "/tmp/dhcpservd_ready" REDIS_SOCK_PATH = "/var/run/redis/redis.sock" @@ -23,18 +26,50 @@ DHCP_SERVER_INTERFACE = "eth0" AF_INET = 2 DEFAULT_SELECT_TIMEOUT = 5000 # millisecond +RECOVERY_CHECKERS = { + "DhcpServerTableCfgChangeEventChecker", + "DhcpPortTableEventChecker", + "DhcpMatchTableEventChecker", + "DhcpBindingTableEventChecker", + "DhcpOptionTableEventChecker", + "DhcpRangeTableEventChecker", + "VlanTableEventChecker", + "VlanIntfTableEventChecker", + "VlanMemberTableEventChecker", + "MidPlaneTableEventChecker", + "DpusTableEventChecker" +} class DhcpServd(object): enabled_checker = None dhcp_servd_monitor = None - def __init__(self, dhcp_cfg_generator, db_connector, monitor, kea_dhcp4_config_path=KEA_DHCP4_CONFIG): + def __init__(self, dhcp_cfg_generator, db_connector, monitor, kea_dhcp4_config_path=KEA_DHCP4_CONFIG, + kea_dhcp4_binary=KEA_DHCP4_PROC_NAME): self.dhcp_cfg_generator = dhcp_cfg_generator self.db_connector = db_connector self.kea_dhcp4_config_path = kea_dhcp4_config_path + self.kea_dhcp4_binary = kea_dhcp4_binary self.dhcp_servd_monitor = monitor self.enabled_checker = None + self.used_range = set() + self.enabled_dhcp_interfaces = set() + self.enabled_port_interfaces = set() + self.enabled_match_interfaces = set() + self.used_options = set() + self.used_matches = set() + self.recovery_checkers = set() + self.reload_pending = False + + def _enable_recovery_checkers(self): + if self.enabled_checker is None or self.dhcp_servd_monitor is None: + return + currently_enabled = self.enabled_checker | self.recovery_checkers + missing_checkers = RECOVERY_CHECKERS - currently_enabled + if missing_checkers: + self.dhcp_servd_monitor.enable_checkers(missing_checkers) + self.recovery_checkers |= missing_checkers def _notify_kea_dhcp4_proc(self): """ @@ -50,22 +85,86 @@ def _notify_kea_dhcp4_proc(self): def dump_dhcp4_config(self): """ - Generate kea-dhcp4 config file and dump it to config folder + Generate and validate a candidate config, then atomically activate it. """ - kea_dhcp4_config, used_ranges, enabled_dhcp_interfaces, used_options, enable_checker = \ - self.dhcp_cfg_generator.generate() - if self.enabled_checker is not None and self.enabled_checker != enable_checker: + try: + generation_result = self.dhcp_cfg_generator.generate() + except ValueError as error: + syslog.syslog(syslog.LOG_ERR, "Cannot generate Kea candidate config: {}".format(error)) + self.reload_pending = True + self._enable_recovery_checkers() + return False + kea_dhcp4_config, used_ranges, enabled_dhcp_interfaces, used_options, enable_checker, \ + enabled_port_interfaces, enabled_match_interfaces, used_matches = generation_result + + config_dir = os.path.dirname(self.kea_dhcp4_config_path) or "." + candidate_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + dir=config_dir, + prefix=".{}.".format(os.path.basename(self.kea_dhcp4_config_path)), + delete=False + ) as candidate: + candidate.write(kea_dhcp4_config) + candidate.flush() + os.fsync(candidate.fileno()) + candidate_path = candidate.name + + validation = subprocess.run( + [self.kea_dhcp4_binary, "-t", candidate_path], + capture_output=True, + text=True, + timeout=KEA_VALIDATION_TIMEOUT + ) + if validation.returncode != 0: + validation_output = validation.stderr.strip() or validation.stdout.strip() + syslog.syslog( + syslog.LOG_ERR, + "Kea rejected candidate config {}: {}".format(candidate_path, validation_output) + ) + self.reload_pending = True + self._enable_recovery_checkers() + return False + + os.replace(candidate_path, self.kea_dhcp4_config_path) + candidate_path = None + except (OSError, subprocess.SubprocessError) as error: + syslog.syslog( + syslog.LOG_ERR, + "Cannot validate or activate Kea candidate config: {}".format(error) + ) + self.reload_pending = True + self._enable_recovery_checkers() + return False + finally: + if candidate_path is not None: + try: + os.unlink(candidate_path) + except FileNotFoundError: + pass + + currently_enabled = (self.enabled_checker or set()) | self.recovery_checkers + if self.enabled_checker is not None and currently_enabled != enable_checker: # Has subcribe table and no equal, need to resubscribe - self.dhcp_servd_monitor.disable_checkers(self.enabled_checker - enable_checker) - self.dhcp_servd_monitor.enable_checkers(enable_checker - self.enabled_checker) + disabled_checkers = currently_enabled - enable_checker + enabled_checkers = enable_checker - currently_enabled + if disabled_checkers: + self.dhcp_servd_monitor.disable_checkers(disabled_checkers) + if enabled_checkers: + self.dhcp_servd_monitor.enable_checkers(enabled_checkers) self.enabled_checker = enable_checker + self.recovery_checkers = set() + self.reload_pending = False self.used_range = used_ranges self.enabled_dhcp_interfaces = enabled_dhcp_interfaces + self.enabled_port_interfaces = enabled_port_interfaces + self.enabled_match_interfaces = enabled_match_interfaces self.used_options = used_options - with open(self.kea_dhcp4_config_path, "w") as write_file: - write_file.write(kea_dhcp4_config) + self.used_matches = used_matches # After refresh kea-config, we need to SIGHUP kea-dhcp4 process to read new config self._notify_kea_dhcp4_proc() + return True def _update_dhcp_server_ip(self): """ @@ -89,7 +188,9 @@ def _update_dhcp_server_ip(self): def start(self): start_time = time.time() syslog.syslog(syslog.LOG_INFO, "dhcpservd starting") - self.dump_dhcp4_config() + if not self.dump_dhcp4_config(): + syslog.syslog(syslog.LOG_ERR, "Initial Kea configuration validation failed, exiting") + sys.exit(1) syslog.syslog(syslog.LOG_INFO, "dump_dhcp4_config done, elapsed=%.3fs" % (time.time() - start_time)) self._update_dhcp_server_ip() syslog.syslog(syslog.LOG_INFO, "update_dhcp_server_ip done, elapsed=%.3fs" % (time.time() - start_time)) @@ -113,10 +214,13 @@ def _signal_readiness(self): def wait(self): while True: - db_snapshot = { + db_snapshot = {} if self.reload_pending else { "enabled_dhcp_interfaces": self.enabled_dhcp_interfaces, + "enabled_port_interfaces": self.enabled_port_interfaces, + "enabled_match_interfaces": self.enabled_match_interfaces, "used_range": self.used_range, - "used_options": self.used_options + "used_options": self.used_options, + "used_matches": self.used_matches } res = self.dhcp_servd_monitor.check_db_update(db_snapshot) if res: @@ -135,6 +239,8 @@ def main(): checkers = [] checkers.append(DhcpServerTableCfgChangeEventChecker(sel, dhcp_db_connector.config_db)) checkers.append(DhcpPortTableEventChecker(sel, dhcp_db_connector.config_db)) + checkers.append(DhcpMatchTableEventChecker(sel, dhcp_db_connector.config_db)) + checkers.append(DhcpBindingTableEventChecker(sel, dhcp_db_connector.config_db)) checkers.append(DhcpOptionTableEventChecker(sel, dhcp_db_connector.config_db)) checkers.append(DhcpRangeTableEventChecker(sel, dhcp_db_connector.config_db)) checkers.append(VlanTableEventChecker(sel, dhcp_db_connector.config_db)) diff --git a/src/sonic-dhcp-utilities/tests/test_dhcp_cfggen.py b/src/sonic-dhcp-utilities/tests/test_dhcp_cfggen.py index 9526566f7ee..b03d5c0a3ec 100644 --- a/src/sonic-dhcp-utilities/tests/test_dhcp_cfggen.py +++ b/src/sonic-dhcp-utilities/tests/test_dhcp_cfggen.py @@ -410,9 +410,13 @@ def test_parse_port(test_config_db, mock_swsscommon_dbconnector_init, mock_get_r def test_generate(mock_swsscommon_dbconnector_init, mock_parse_port_map_alias, mock_get_render_template): with patch.object(DhcpServCfgGenerator, "_parse_hostname"), \ patch.object(DhcpServCfgGenerator, "_parse_vlan", return_value=({}, set(["Ethernet0"]))), \ - patch.object(DhcpServCfgGenerator, "_get_dhcp_ipv4_tables_from_db", return_value=(None, None, None, None)), \ + patch.object(DhcpServCfgGenerator, "_get_dhcp_ipv4_tables_from_db", + return_value=({"Vlan1000": {"state": "enabled", "mode": "PORT"}}, + None, None, None, None, None)), \ patch.object(DhcpServCfgGenerator, "_parse_range"), \ patch.object(DhcpServCfgGenerator, "_parse_port", return_value=(None, set(["range1"]))), \ + patch.object(DhcpServCfgGenerator, "_parse_match_bindings", + return_value=({}, [], set(["range2"]), set(["match1"]))), \ patch.object(DhcpServCfgGenerator, "_parse_customized_options"), \ patch.object(DhcpServCfgGenerator, "_parse_dpu", return_value=(set(), set())), \ patch.object(DhcpServCfgGenerator, "_construct_obj_for_template", @@ -422,14 +426,17 @@ def test_generate(mock_swsscommon_dbconnector_init, mock_parse_port_map_alias, m patch("dhcp_utilities.dhcpservd.dhcp_cfggen.is_smart_switch", return_value=False): dhcp_db_connector = DhcpDbConnector() dhcp_cfg_generator = DhcpServCfgGenerator(dhcp_db_connector, "/usr/local/lib/kea/hooks/libdhcp_run_script.so") - kea_dhcp4_config, used_ranges, enabled_dhcp_interfaces, used_options, subscribe_table = \ - dhcp_cfg_generator.generate() + kea_dhcp4_config, used_ranges, enabled_dhcp_interfaces, used_options, subscribe_table, \ + enabled_port_interfaces, enabled_match_interfaces, used_matches = dhcp_cfg_generator.generate() assert kea_dhcp4_config == "dummy_config" - assert used_ranges == set(["range1"]) + assert used_ranges == set(["range1", "range2"]) assert enabled_dhcp_interfaces == set(["Vlan1000"]) assert used_options == set(["option1"]) expected_tables = set(["dummy"]) assert subscribe_table == expected_tables + assert enabled_port_interfaces == set(["Vlan1000"]) + assert enabled_match_interfaces == set() + assert used_matches == set(["match1"]) def test_construct_obj_for_template(mock_swsscommon_dbconnector_init, mock_parse_port_map_alias, diff --git a/src/sonic-dhcp-utilities/tests/test_dhcp_db_monitor.py b/src/sonic-dhcp-utilities/tests/test_dhcp_db_monitor.py index 86c34663b48..0bd965e2c8c 100644 --- a/src/sonic-dhcp-utilities/tests/test_dhcp_db_monitor.py +++ b/src/sonic-dhcp-utilities/tests/test_dhcp_db_monitor.py @@ -4,7 +4,8 @@ PORT_MODE_CHECKER, mock_exit_func from dhcp_utilities.common.dhcp_db_monitor import DhcpRelaydDbMonitor, DhcpServdDbMonitor, ConfigDbEventChecker, \ DhcpServerTableIntfEnablementEventChecker, DhcpServerTableCfgChangeEventChecker, \ - DhcpPortTableEventChecker, DhcpRangeTableEventChecker, DhcpOptionTableEventChecker, \ + DhcpPortTableEventChecker, DhcpMatchTableEventChecker, DhcpBindingTableEventChecker, \ + DhcpRangeTableEventChecker, DhcpOptionTableEventChecker, \ VlanTableEventChecker, VlanMemberTableEventChecker, VlanIntfTableEventChecker, DhcpServerFeatureStateChecker, \ MidPlaneTableEventChecker, DpusTableEventChecker from dhcp_utilities.common.utils import DhcpDbConnector @@ -102,6 +103,24 @@ def test_dhcp_servd_monitor_check_db_update(mock_swsscommon_dbconnector_init, se mock_clear.assert_not_called() +def test_dhcp_servd_monitor_recovery_consumes_pending_events(mock_swsscommon_dbconnector_init): + with patch.object(swsscommon.Select, "select", return_value=(swsscommon.Select.OBJECT, None)), \ + patch.object(ConfigDbEventChecker, "is_enabled", return_value=True), \ + patch.object(ConfigDbEventChecker, "clear_event") as mock_clear, \ + patch.object(ConfigDbEventChecker, "check_update_event") as mock_check: + db_connector = DhcpDbConnector() + checkers = [ + DhcpServerTableCfgChangeEventChecker(None, None), + DhcpMatchTableEventChecker(None, None) + ] + db_monitor = DhcpServdDbMonitor(db_connector, swsscommon.Select(), checkers) + + assert db_monitor.check_db_update({}) + + assert mock_clear.call_count == len(checkers) + mock_check.assert_not_called() + + @pytest.mark.parametrize("tables", [set(["VlanIntfTableEventChecker"]), set(["dummy1"])]) def test_dhcp_servd_monitor_enable_checkers(mock_swsscommon_dbconnector_init, tables): with patch.object(ConfigDbEventChecker, "enable") as mock_enable: @@ -248,7 +267,7 @@ def test_dhcp_server_table_enablement_change_checker(mock_swsscommon_dbconnector assert expected_res == check_res -@pytest.mark.parametrize("tested_db_snapshot", [{"enabled_dhcp_interfaces": {"Vlan1000"}}, {}]) +@pytest.mark.parametrize("tested_db_snapshot", [{"enabled_port_interfaces": {"Vlan1000"}}, {}]) @pytest.mark.parametrize("tested_data", get_subscribe_table_tested_data("test_port_update")) def test_dhcp_port_table_checker(mock_swsscommon_dbconnector_init, tested_data, tested_db_snapshot): with patch.object(ConfigDbEventChecker, "enable"), \ @@ -259,12 +278,37 @@ def test_dhcp_port_table_checker(mock_swsscommon_dbconnector_init, tested_data, db_event_checker = DhcpPortTableEventChecker(sel, MagicMock()) expected_res = tested_data["exp_res"] check_res = db_event_checker.check_update_event(tested_db_snapshot) - if "enabled_dhcp_interfaces" not in tested_db_snapshot: + if "enabled_port_interfaces" not in tested_db_snapshot: assert check_res else: assert expected_res == check_res +@pytest.mark.parametrize("match_name,expected", [("vendor-a", True), ("vendor-b", False)]) +def test_dhcp_match_table_checker(mock_swsscommon_dbconnector_init, match_name, expected): + tested_data = [(match_name, "SET", (("value", "updated"),))] + with patch.object(ConfigDbEventChecker, "enable"), \ + patch.object(ConfigDbEventChecker, "subscriber_state_table", + return_value=MockSubscribeTable(tested_data), new_callable=PropertyMock), \ + patch.object(sys, "exit"): + checker = DhcpMatchTableEventChecker(swsscommon.Select(), MagicMock()) + assert checker.check_update_event({"used_matches": {"vendor-a"}}) == expected + + +@pytest.mark.parametrize("binding_key,expected", [ + ("Vlan1000|binding-a", True), + ("Vlan2000|binding-a", False) +]) +def test_dhcp_binding_table_checker(mock_swsscommon_dbconnector_init, binding_key, expected): + tested_data = [(binding_key, "SET", (("matches", "vendor-a"),))] + with patch.object(ConfigDbEventChecker, "enable"), \ + patch.object(ConfigDbEventChecker, "subscriber_state_table", + return_value=MockSubscribeTable(tested_data), new_callable=PropertyMock), \ + patch.object(sys, "exit"): + checker = DhcpBindingTableEventChecker(swsscommon.Select(), MagicMock()) + assert checker.check_update_event({"enabled_match_interfaces": {"Vlan1000"}}) == expected + + @pytest.mark.parametrize("tested_db_snapshot", [{"used_range": {"range1"}}, {}]) @pytest.mark.parametrize("tested_data", get_subscribe_table_tested_data("test_range_update")) def test_dhcp_range_table_checker(mock_swsscommon_dbconnector_init, tested_data, tested_db_snapshot): diff --git a/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py new file mode 100644 index 00000000000..60e8fe95776 --- /dev/null +++ b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py @@ -0,0 +1,435 @@ +import ipaddress +import json +from unittest.mock import patch + +import pytest + +from dhcp_utilities.common.utils import DhcpDbConnector +from dhcp_utilities.dhcpservd.dhcp_cfggen import DhcpServCfgGenerator, MATCH_MODE_CHECKER, PORT_MODE_CHECKER + + +DHCP_SERVERS = { + "Vlan1000": { + "gateway": "192.168.0.1", + "lease_time": "900", + "mode": "MATCH", + "state": "enabled" + } +} +DHCP_INTERFACES = { + "Vlan1000": [{ + "network": ipaddress.ip_network("192.168.0.0/24"), + "ip": "192.168.0.1/24" + }] +} +VLAN_MEMBERS = {"Vlan1000|Ethernet24"} +RANGES = { + "fallback-range": [ + ipaddress.ip_address("192.168.0.30"), + ipaddress.ip_address("192.168.0.30") + ] +} +MATCHES = { + "port-etp7": {"type": "circuit_id", "value": "etp7"}, + "vendor-a": {"type": "option60", "value": "MAIA-A"}, + "vendor-b": {"type": "option60", "value": "MAIA-B"} +} + + +class DictConnector: + def __init__(self, tables): + self.tables = tables + + def get_config_db_table(self, table_name): + return self.tables.get(table_name, {}) + + +def create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template): + with patch.object(DhcpServCfgGenerator, "_parse_port_map_alias"): + generator = DhcpServCfgGenerator( + DhcpDbConnector(), + "/usr/local/lib/kea/hooks/libdhcp_run_script.so" + ) + generator.port_alias_map = { + "Ethernet24": "etp7", + "Ethernet28": "etp8" + } + return generator + + +def parse_bindings(generator, bindings, matches=None, servers=None, interfaces=None, members=None, ranges=None): + return generator._parse_match_bindings( + servers if servers is not None else DHCP_SERVERS, + matches if matches is not None else MATCHES, + bindings, + interfaces if interfaces is not None else DHCP_INTERFACES, + members if members is not None else VLAN_MEMBERS, + ranges if ranges is not None else RANGES, + "sonic-host" + ) + + +def get_class_for_pool(pools, classes, pool_range): + class_name = next(pool["client_class"] for pool in pools if pool["range"] == pool_range) + return next(client_class for client_class in classes if client_class["name"] == class_name) + + +def test_parse_match_bindings_specificity_fallback(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = { + "Vlan1000|specific": { + "matches": ["port-etp7", "vendor-a"], + "ips": ["192.168.0.20"] + }, + "Vlan1000|fallback": { + "matches": ["port-etp7"], + "ranges": ["fallback-range"] + } + } + + pools, classes, used_ranges, used_matches = parse_bindings(generator, bindings) + + subnet_pools = pools["Vlan1000"]["192.168.0.1/24"] + specific_class = get_class_for_pool(subnet_pools, classes, "192.168.0.20 - 192.168.0.20") + fallback_class = get_class_for_pool(subnet_pools, classes, "192.168.0.30 - 192.168.0.30") + assert "relay4[1].exists" in specific_class["condition"] + assert "option[60].exists" in specific_class["condition"] + assert "0x736f6e69632d686f73743a65747037" in specific_class["condition"] + assert "0x4d4149412d41" in specific_class["condition"] + assert "not" not in specific_class["condition"] + assert "not" in fallback_class["condition"] + assert used_ranges == {"fallback-range"} + assert used_matches == {"port-etp7", "vendor-a"} + + +def test_identical_pool_bindings_are_grouped_with_or(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = { + "Vlan1000|vendor-a": { + "matches": ["vendor-a"], + "ips": ["192.168.0.20"] + }, + "Vlan1000|vendor-b": { + "matches": ["vendor-b"], + "ips": ["192.168.0.20"] + } + } + + pools, classes, _, _ = parse_bindings(generator, bindings) + + assert len(pools["Vlan1000"]["192.168.0.1/24"]) == 1 + assert len(classes) == 1 + assert " or " in classes[0]["condition"] + assert "0x4d4149412d41" in classes[0]["condition"] + assert "0x4d4149412d42" in classes[0]["condition"] + + +def test_adjacent_match_ips_are_normalized(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = { + "Vlan1000|vendor-a": { + "matches": ["vendor-a"], + "ips": ["192.168.0.21", "192.168.0.20"] + } + } + + pools, _, _, _ = parse_bindings(generator, bindings) + + assert pools["Vlan1000"]["192.168.0.1/24"][0]["range"] == "192.168.0.20 - 192.168.0.21" + + +def test_four_bindings_on_one_port(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + matches = {"port-etp7": MATCHES["port-etp7"]} + bindings = {} + for index in range(4): + match_name = "vendor-{}".format(index) + matches[match_name] = {"type": "option60", "value": "VENDOR-{}".format(index)} + bindings["Vlan1000|binding-{}".format(index)] = { + "matches": ["port-etp7", match_name], + "ips": ["192.168.0.{}".format(20 + index)] + } + + pools, classes, _, used_matches = parse_bindings(generator, bindings, matches=matches) + + assert len(pools["Vlan1000"]["192.168.0.1/24"]) == 4 + assert len(classes) == 4 + assert len(used_matches) == 5 + + +def test_match_compilation_is_deterministic(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = { + "Vlan1000|vendor-b": { + "matches": ["vendor-b", "port-etp7"], + "ips": ["192.168.0.21"] + }, + "Vlan1000|vendor-a": { + "matches": ["port-etp7", "vendor-a"], + "ips": ["192.168.0.20"] + } + } + + first = parse_bindings(generator, bindings) + second = parse_bindings(generator, dict(reversed(list(bindings.items())))) + + assert first == second + + +@pytest.mark.parametrize("bindings,error", [ + ({}, "requires at least one binding"), + ({ + "Vlan1000|missing": { + "matches": ["missing-match"], + "ips": ["192.168.0.20"] + } + }, "does not exist"), + ({ + "Vlan1000|duplicate-type": { + "matches": ["vendor-a", "vendor-b"], + "ips": ["192.168.0.20"] + } + }, "multiple matches of type option60"), + ({ + "Vlan1000|outside": { + "matches": ["vendor-a"], + "ips": ["192.168.1.20"] + } + }, "is not in an IPv4 subnet") +]) +def test_invalid_match_bindings_are_rejected(mock_swsscommon_dbconnector_init, mock_get_render_template, + bindings, error): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + + with pytest.raises(ValueError, match=error): + parse_bindings(generator, bindings) + + +def test_equal_specificity_overlap_is_rejected(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = { + "Vlan1000|port-only": { + "matches": ["port-etp7"], + "ips": ["192.168.0.20"] + }, + "Vlan1000|vendor-only": { + "matches": ["vendor-a"], + "ips": ["192.168.0.21"] + } + } + + with pytest.raises(ValueError, match="overlap with equal specificity"): + parse_bindings(generator, bindings) + + +def test_partial_pool_overlap_is_rejected(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + ranges = { + "range-a": [ipaddress.ip_address("192.168.0.20"), ipaddress.ip_address("192.168.0.30")], + "range-b": [ipaddress.ip_address("192.168.0.25"), ipaddress.ip_address("192.168.0.35")] + } + bindings = { + "Vlan1000|vendor-a": { + "matches": ["vendor-a"], + "ranges": ["range-a"] + }, + "Vlan1000|vendor-b": { + "matches": ["vendor-b"], + "ranges": ["range-b"] + } + } + + with pytest.raises(ValueError, match="partially overlapping pools"): + parse_bindings(generator, bindings, ranges=ranges) + + +def test_circuit_id_must_be_vlan_member(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = { + "Vlan1000|port-only": { + "matches": ["port-etp7"], + "ips": ["192.168.0.20"] + } + } + + with pytest.raises(ValueError, match="is not a member"): + parse_bindings(generator, bindings, members={"Vlan1000|Ethernet28"}) + + +def test_match_value_byte_limit_is_enforced(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + matches = { + "oversized": {"type": "option60", "value": "é" * 128} + } + bindings = { + "Vlan1000|oversized": { + "matches": ["oversized"], + "ips": ["192.168.0.20"] + } + } + + with pytest.raises(ValueError, match="payload limit"): + parse_bindings(generator, bindings, matches=matches) + + +def test_mixed_port_and_match_rendering(mock_swsscommon_dbconnector_init): + with patch.object(DhcpServCfgGenerator, "_parse_port_map_alias"): + generator = DhcpServCfgGenerator( + DhcpDbConnector(), + "/usr/local/lib/kea/hooks/libdhcp_run_script.so", + kea_conf_template_path="tests/test_data/kea-dhcp4.conf.j2" + ) + generator.port_alias_map = {"Ethernet24": "etp7"} + servers = { + "Vlan1000": {"mode": "PORT", "state": "enabled", "lease_time": "900"}, + "Vlan2000": {"mode": "MATCH", "state": "enabled", "lease_time": "900"} + } + interfaces = { + "Vlan2000": [{ + "network": ipaddress.ip_network("192.168.1.0/24"), + "ip": "192.168.1.1/24" + }] + } + bindings = { + "Vlan2000|vendor-a": { + "matches": ["vendor-a"], + "ips": ["192.168.1.20"] + } + } + match_pools, match_classes, _, _ = parse_bindings( + generator, + bindings, + servers=servers, + interfaces=interfaces, + members=set() + ) + port_pools = { + "Vlan1000": { + "192.168.0.1/24": { + "etp7": [["192.168.0.20", "192.168.0.20"]] + } + } + } + + render_obj, enabled_interfaces, _, checkers = generator._construct_obj_for_template( + servers, + port_pools, + "sonic-host", + {}, + match_pools=match_pools, + match_client_classes=match_classes + ) + rendered = json.loads(generator._render_config(render_obj)) + + assert enabled_interfaces == {"Vlan1000", "Vlan2000"} + assert checkers == set(PORT_MODE_CHECKER) | set(MATCH_MODE_CHECKER) + assert {subnet["subnet"] for subnet in rendered["Dhcp4"]["subnet4"]} == { + "192.168.0.0/24", "192.168.1.0/24" + } + assert len(rendered["Dhcp4"]["client-classes"]) == 2 + + +def test_match_mode_uses_midplane_subnet_id_on_smart_switch( + mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + match_pools, match_client_classes, _, _ = parse_bindings( + generator, + { + "Vlan1000|binding-a": { + "matches": ["port-etp7"], + "ranges": ["range-a"] + } + }, + ranges={ + "range-a": [ + ipaddress.ip_address("192.168.0.20"), + ipaddress.ip_address("192.168.0.20") + ] + } + ) + render_obj, _, _, _ = generator._construct_obj_for_template( + DHCP_SERVERS, + {}, + "sonic-host", + {}, + smart_switch=True, + match_pools=match_pools, + match_client_classes=match_client_classes + ) + + assert render_obj["subnets"][0]["id"] == 10000 + + +def test_generate_match_config_and_snapshots(): + tables = { + "DEVICE_METADATA": {"localhost": {"hostname": "sonic-host"}}, + "VLAN_INTERFACE": { + "Vlan1000": {}, + "Vlan1000|192.168.0.1/24": {} + }, + "VLAN_MEMBER": { + "Vlan1000|Ethernet24": {} + }, + "PORT": { + "Ethernet24": {"alias": "etp7"} + }, + "PORTCHANNEL": {}, + "DPUS": {}, + "MID_PLANE_BRIDGE": {}, + "DHCP_SERVER_IPV4": { + "Vlan1000": { + "gateway": "192.168.0.1", + "lease_time": "900", + "mode": "MATCH", + "state": "enabled" + }, + "Vlan2000": { + "lease_time": "900", + "mode": "MATCH", + "state": "disabled" + } + }, + "DHCP_SERVER_IPV4_CUSTOMIZED_OPTIONS": {}, + "DHCP_SERVER_IPV4_RANGE": { + "fallback-range": {"range": ["192.168.0.30"]} + }, + "DHCP_SERVER_IPV4_PORT": {}, + "DHCP_SERVER_IPV4_MATCH": { + **MATCHES, + "unused": {"type": "unsupported", "value": ""} + }, + "DHCP_SERVER_IPV4_BINDING": { + "Vlan1000|specific": { + "matches": ["port-etp7", "vendor-a"], + "ips": ["192.168.0.20"] + }, + "Vlan1000|fallback": { + "matches": ["port-etp7"], + "ranges": ["fallback-range"] + }, + "Vlan2000|inactive-invalid": { + "matches": ["missing"], + "ranges": ["missing"] + } + } + } + generator = DhcpServCfgGenerator( + DictConnector(tables), + "/usr/local/lib/kea/hooks/libdhcp_run_script.so", + kea_conf_template_path="tests/test_data/kea-dhcp4.conf.j2" + ) + + config, used_ranges, enabled_interfaces, used_options, checkers, enabled_port_interfaces, \ + enabled_match_interfaces, used_matches = generator.generate() + parsed_config = json.loads(config) + + assert len(parsed_config["Dhcp4"]["subnet4"]) == 1 + assert len(parsed_config["Dhcp4"]["subnet4"][0]["pools"]) == 2 + assert len(parsed_config["Dhcp4"]["client-classes"]) == 2 + assert used_ranges == {"fallback-range"} + assert enabled_interfaces == {"Vlan1000"} + assert used_options == set() + assert checkers == set(MATCH_MODE_CHECKER) + assert enabled_port_interfaces == set() + assert enabled_match_interfaces == {"Vlan1000"} + assert used_matches == {"port-etp7", "vendor-a"} diff --git a/src/sonic-dhcp-utilities/tests/test_dhcpservd.py b/src/sonic-dhcp-utilities/tests/test_dhcpservd.py index ffaade23f27..b1786b79181 100644 --- a/src/sonic-dhcp-utilities/tests/test_dhcpservd.py +++ b/src/sonic-dhcp-utilities/tests/test_dhcpservd.py @@ -1,16 +1,17 @@ import pytest import json import psutil -import signal import sys import time +from types import SimpleNamespace from common_utils import MockProc, mock_get_config_db_table from dhcp_utilities.common.utils import DhcpDbConnector from dhcp_utilities.common.dhcp_db_monitor import DhcpServdDbMonitor from dhcp_utilities.dhcpservd.dhcp_cfggen import DhcpServCfgGenerator +from dhcp_utilities.dhcpservd.dhcp_lease import LeaseManager from dhcp_utilities.dhcpservd.dhcpservd import DhcpServd from swsscommon import swsscommon -from unittest.mock import patch, call, MagicMock, PropertyMock +from unittest.mock import patch, call, MagicMock AF_INET = 2 AF_INET6 = 10 @@ -27,39 +28,184 @@ @pytest.mark.parametrize("enabled_checker", [None, set(PORT_MODE_CHECKER)]) -def test_dump_dhcp4_config(mock_swsscommon_dbconnector_init, enabled_checker): +def test_dump_dhcp4_config(mock_swsscommon_dbconnector_init, enabled_checker, tmp_path): new_enabled_checker = set(["VlanTableEventChecker"]) - with patch("dhcp_utilities.dhcpservd.dhcp_cfggen.DhcpServCfgGenerator.generate", - return_value=(tested_config, set(), set(), set(), new_enabled_checker)) as mock_generate, \ - patch("dhcp_utilities.dhcpservd.dhcpservd.DhcpServd._notify_kea_dhcp4_proc", - MagicMock()) as mock_notify_kea_dhcp4_proc, \ - patch.object(DhcpServd, "dhcp_servd_monitor", return_value=DhcpServdDbMonitor, - new_callable=PropertyMock), \ - patch.object(DhcpServdDbMonitor, "disable_checkers") as mock_unsubscribe, \ - patch.object(DhcpServdDbMonitor, "enable_checkers") as mock_subscribe, \ - patch.object(DhcpServd, "enabled_checker", return_value=enabled_checker, new_callable=PropertyMock), \ - patch.object(DhcpServCfgGenerator, "_parse_port_map_alias"): - dhcp_db_connector = DhcpDbConnector() - dhcp_cfg_generator = DhcpServCfgGenerator(dhcp_db_connector, "/usr/local/lib/kea/hooks/libdhcp_run_script.so", - kea_conf_template_path="tests/test_data/kea-dhcp4.conf.j2") - dhcpservd = DhcpServd(dhcp_cfg_generator, dhcp_db_connector, None, - kea_dhcp4_config_path="/tmp/kea-dhcp4.conf") - dhcpservd.dump_dhcp4_config() + generation_result = ( + tested_config, + {"range1"}, + {"Vlan1000"}, + {"option223"}, + new_enabled_checker, + {"Vlan1000"}, + set(), + {"vendor-a"} + ) + dhcp_cfg_generator = MagicMock() + dhcp_cfg_generator.generate.return_value = generation_result + monitor = MagicMock() + config_path = tmp_path / "kea-dhcp4.conf" + with patch("dhcp_utilities.dhcpservd.dhcpservd.DhcpServd._notify_kea_dhcp4_proc") \ + as mock_notify_kea_dhcp4_proc, \ + patch("dhcp_utilities.dhcpservd.dhcpservd.subprocess.run", + return_value=SimpleNamespace(returncode=0, stdout="", stderr="")) as mock_validate: + dhcpservd = DhcpServd( + dhcp_cfg_generator, + MagicMock(), + monitor, + kea_dhcp4_config_path=str(config_path), + kea_dhcp4_binary="kea-dhcp4" + ) + dhcpservd.enabled_checker = enabled_checker + assert dhcpservd.dump_dhcp4_config() # Verfiy whether generate() func of dhcp_cfggen is called - mock_generate.assert_called_once_with() + dhcp_cfg_generator.generate.assert_called_once_with() + validate_args = mock_validate.call_args.args[0] + assert validate_args[:2] == ["kea-dhcp4", "-t"] + assert validate_args[2] != str(config_path) with open("tests/test_data/test_kea_config.conf", "r") as file, \ - open("/tmp/kea-dhcp4.conf", "r") as output: + open(config_path, "r") as output: expected_content = file.read() actual_content = output.read() assert json.loads(expected_content) == json.loads(actual_content) # Verify whether notify func of dhcpservd is called, which is expected to call after new config generated mock_notify_kea_dhcp4_proc.assert_called_once_with() if enabled_checker is None: - mock_subscribe.assert_not_called() - mock_unsubscribe.assert_not_called() + monitor.enable_checkers.assert_not_called() + monitor.disable_checkers.assert_not_called() else: - mock_unsubscribe.assert_called_once_with(enabled_checker - new_enabled_checker) - mock_subscribe.assert_called_once_with(new_enabled_checker - enabled_checker) + monitor.disable_checkers.assert_called_once_with(enabled_checker - new_enabled_checker) + monitor.enable_checkers.assert_not_called() + assert dhcpservd.used_range == {"range1"} + assert dhcpservd.enabled_port_interfaces == {"Vlan1000"} + assert dhcpservd.enabled_match_interfaces == set() + assert dhcpservd.used_matches == {"vendor-a"} + + +def test_dump_dhcp4_config_validation_failure_preserves_live_config(mock_swsscommon_dbconnector_init, tmp_path): + config_path = tmp_path / "kea-dhcp4.conf" + config_path.write_text("last-known-good") + generator = MagicMock() + generator.generate.return_value = ( + tested_config, {"new-range"}, {"Vlan2000"}, {"new-option"}, {"NewChecker"}, + set(), {"Vlan2000"}, {"new-match"} + ) + monitor = MagicMock() + with patch("dhcp_utilities.dhcpservd.dhcpservd.subprocess.run", + return_value=SimpleNamespace(returncode=1, stdout="", stderr="invalid config")), \ + patch.object(DhcpServd, "_notify_kea_dhcp4_proc") as mock_notify: + dhcpservd = DhcpServd( + generator, + MagicMock(), + monitor, + kea_dhcp4_config_path=str(config_path) + ) + dhcpservd.enabled_checker = {"OldChecker"} + dhcpservd.used_range = {"old-range"} + + assert not dhcpservd.dump_dhcp4_config() + + assert config_path.read_text() == "last-known-good" + assert list(tmp_path.iterdir()) == [config_path] + assert dhcpservd.enabled_checker == {"OldChecker"} + assert dhcpservd.used_range == {"old-range"} + monitor.disable_checkers.assert_not_called() + monitor.enable_checkers.assert_called_once() + recovery_checkers = monitor.enable_checkers.call_args.args[0] + assert "MidPlaneTableEventChecker" in recovery_checkers + assert "DpusTableEventChecker" in recovery_checkers + mock_notify.assert_not_called() + assert dhcpservd.reload_pending + assert dhcpservd.recovery_checkers + + +def test_dump_dhcp4_config_generation_failure_preserves_live_config(mock_swsscommon_dbconnector_init, tmp_path): + config_path = tmp_path / "kea-dhcp4.conf" + config_path.write_text("last-known-good") + generator = MagicMock() + generator.generate.side_effect = ValueError("invalid binding") + monitor = MagicMock() + with patch.object(DhcpServd, "_notify_kea_dhcp4_proc") as mock_notify: + dhcpservd = DhcpServd(generator, MagicMock(), monitor, kea_dhcp4_config_path=str(config_path)) + dhcpservd.enabled_checker = {"DhcpServerTableCfgChangeEventChecker"} + + assert not dhcpservd.dump_dhcp4_config() + + assert config_path.read_text() == "last-known-good" + assert dhcpservd.enabled_checker == {"DhcpServerTableCfgChangeEventChecker"} + assert dhcpservd.reload_pending + monitor.enable_checkers.assert_called_once() + mock_notify.assert_not_called() + + +def test_dump_dhcp4_config_validation_execution_failure_preserves_live_config( + mock_swsscommon_dbconnector_init, tmp_path): + config_path = tmp_path / "kea-dhcp4.conf" + config_path.write_text("last-known-good") + generator = MagicMock() + generator.generate.return_value = ( + tested_config, set(), {"Vlan1000"}, set(), {"NewChecker"}, + set(), {"Vlan1000"}, {"new-match"} + ) + monitor = MagicMock() + with patch("dhcp_utilities.dhcpservd.dhcpservd.subprocess.run", + side_effect=FileNotFoundError("kea-dhcp4")), \ + patch.object(DhcpServd, "_notify_kea_dhcp4_proc") as mock_notify: + dhcpservd = DhcpServd( + generator, + MagicMock(), + monitor, + kea_dhcp4_config_path=str(config_path) + ) + dhcpservd.enabled_checker = {"OldChecker"} + + assert not dhcpservd.dump_dhcp4_config() + + assert config_path.read_text() == "last-known-good" + assert list(tmp_path.iterdir()) == [config_path] + assert dhcpservd.enabled_checker == {"OldChecker"} + assert dhcpservd.reload_pending + monitor.enable_checkers.assert_called_once() + mock_notify.assert_not_called() + + +def test_dump_dhcp4_config_success_clears_recovery_subscriptions(mock_swsscommon_dbconnector_init, tmp_path): + config_path = tmp_path / "kea-dhcp4.conf" + generator = MagicMock() + generator.generate.return_value = ( + tested_config, + set(), + {"Vlan1000"}, + set(), + {"DhcpServerBindingTableCfgChangeEventChecker"}, + set(), + {"Vlan1000"}, + {"match-a"} + ) + monitor = MagicMock() + dhcpservd = DhcpServd(generator, MagicMock(), monitor, kea_dhcp4_config_path=str(config_path)) + dhcpservd.enabled_checker = {"DhcpServerTableCfgChangeEventChecker"} + dhcpservd.recovery_checkers = { + "DhcpServerTableCfgChangeEventChecker", + "DhcpServerBindingTableCfgChangeEventChecker", + "DhcpServerMatchTableCfgChangeEventChecker" + } + dhcpservd.reload_pending = True + + with patch("dhcp_utilities.dhcpservd.dhcpservd.subprocess.run", + return_value=SimpleNamespace(returncode=0, stdout="", stderr="")), \ + patch.object(DhcpServd, "_notify_kea_dhcp4_proc"): + assert dhcpservd.dump_dhcp4_config() + + monitor.disable_checkers.assert_called_once_with({ + "DhcpServerTableCfgChangeEventChecker", + "DhcpServerMatchTableCfgChangeEventChecker" + }) + monitor.enable_checkers.assert_not_called() + assert dhcpservd.enabled_checker == {"DhcpServerBindingTableCfgChangeEventChecker"} + assert dhcpservd.recovery_checkers == set() + assert dhcpservd.reload_pending is False + assert dhcpservd.enabled_match_interfaces == {"Vlan1000"} + assert dhcpservd.used_matches == {"match-a"} @pytest.mark.parametrize("process_list", [["proc1", "proc2", "kea-dhcp4"], ["proc1", "proc2"]]) @@ -68,14 +214,15 @@ def test_notify_kea_dhcp4_proc(process_list, mock_swsscommon_dbconnector_init, m proc_list = [MockProc(process_name) for process_name in process_list] proc_list.append(MockProc("exited_proc", exited=True)) with patch.object(psutil, "process_iter", return_value=proc_list), \ - patch.object(MockProc, "send_signal", MagicMock()) as mock_send_signal: + patch.object(MockProc, "send_signal", MagicMock()) as mock_send_signal, \ + patch("dhcp_utilities.dhcpservd.dhcpservd.signal.SIGHUP", 1, create=True): dhcp_db_connector = DhcpDbConnector() dhcp_cfg_generator = DhcpServCfgGenerator(dhcp_db_connector, "/usr/local/lib/kea/hooks/libdhcp_run_script.so") dhcpservd = DhcpServd(dhcp_cfg_generator, dhcp_db_connector, None) dhcpservd._notify_kea_dhcp4_proc() if "kea-dhcp4" in process_list: mock_send_signal.assert_has_calls([ - call(signal.SIGHUP) + call(1) ]) else: mock_send_signal.assert_not_called() @@ -111,6 +258,7 @@ def test_update_dhcp_server_ip(mock_swsscommon_dbconnector_init, mock_parse_port def test_start(mock_swsscommon_dbconnector_init, mock_parse_port_map_alias, mock_get_render_template): with patch.object(DhcpServd, "dump_dhcp4_config") as mock_dump, \ patch.object(DhcpServd, "_update_dhcp_server_ip") as mock_update_dhcp_server_ip, \ + patch.object(LeaseManager, "start"), \ patch.object(DhcpServdDbMonitor, "enable_checkers"), \ patch.object(DhcpDbConnector, "get_config_db_table", side_effect=mock_get_config_db_table): dhcp_db_connector = DhcpDbConnector() @@ -121,6 +269,15 @@ def test_start(mock_swsscommon_dbconnector_init, mock_parse_port_map_alias, mock mock_update_dhcp_server_ip.assert_called_once_with() +def test_start_exits_when_initial_candidate_is_invalid(mock_swsscommon_dbconnector_init): + with patch.object(DhcpServd, "dump_dhcp4_config", return_value=False), \ + patch.object(sys, "exit", side_effect=SystemExit(1)) as mock_exit: + dhcpservd = DhcpServd(MagicMock(), MagicMock(), MagicMock()) + with pytest.raises(SystemExit): + dhcpservd.start() + mock_exit.assert_called_once_with(1) + + def test_signal_readiness(mock_swsscommon_dbconnector_init): with patch.object(DhcpDbConnector, "get_config_db_table", side_effect=mock_get_config_db_table), \ patch("tempfile.NamedTemporaryFile"): diff --git a/src/sonic-dhcp-utilities/tests/test_smart_switch.py b/src/sonic-dhcp-utilities/tests/test_smart_switch.py index 4d4454d9af8..15aa0989d41 100644 --- a/src/sonic-dhcp-utilities/tests/test_smart_switch.py +++ b/src/sonic-dhcp-utilities/tests/test_smart_switch.py @@ -154,14 +154,17 @@ def test_dhcp_dhcp_cfggen_generate(mock_swsscommon_dbconnector_init, mock_parse_ dhcp_db_connector = DhcpDbConnector() dhcp_cfg_generator = DhcpServCfgGenerator(dhcp_db_connector, "/usr/local/lib/kea/hooks/libdhcp_run_script.so", kea_conf_template_path="tests/test_data/kea-dhcp4.conf.j2") - kea_dhcp4_config, used_ranges, enabled_dhcp_interfaces, used_options, subscribe_table = \ - dhcp_cfg_generator.generate() + kea_dhcp4_config, used_ranges, enabled_dhcp_interfaces, used_options, subscribe_table, \ + enabled_port_interfaces, enabled_match_interfaces, used_matches = dhcp_cfg_generator.generate() print(json.loads(kea_dhcp4_config)) print(expected_kea_config) assert json.loads(kea_dhcp4_config) == expected_kea_config assert used_ranges == set() assert enabled_dhcp_interfaces == set(["bridge-midplane"]) + assert enabled_port_interfaces == set(["bridge-midplane"]) + assert enabled_match_interfaces == set() assert used_options == set(["option60", "option223"]) + assert used_matches == set() expected_tables = set(["DpusTableEventChecker", "MidPlaneTableEventChecker", "VlanTableEventChecker", "VlanIntfTableEventChecker", "DhcpRangeTableEventChecker", "VlanMemberTableEventChecker", "DhcpOptionTableEventChecker", "DhcpPortTableEventChecker", diff --git a/src/sonic-yang-models/doc/Configuration.md b/src/sonic-yang-models/doc/Configuration.md index 96e31f1e71e..4eee16b6b57 100644 --- a/src/sonic-yang-models/doc/Configuration.md +++ b/src/sonic-yang-models/doc/Configuration.md @@ -1294,14 +1294,6 @@ IPV4 DHCP Server related configuration are defined in **DHCP_SERVER_IPV4**, **DH incoming DHCPv4 packet. A condition is referenced by name from **DHCP_SERVER_IPV4_BINDING**; defining one on its own has no effect. -**Note:** This change adds the schema for **DHCP_SERVER_IPV4_MATCH** and -**DHCP_SERVER_IPV4_BINDING** only. The `mode` leaf of **DHCP_SERVER_IPV4** does not accept -`MATCH` yet, and the DHCP server runtime does not read these two tables yet, so entries -configured here are validated against the schema but do not affect address assignment. The -address-selection and Kea-generation behavior described in the rest of this section takes -effect once `MATCH` mode and the corresponding `dhcpservd` support are added in a follow-up -change. - | Field | Description | | ----- | ----------- | | name | Key. User-defined name of the condition. Must not start or end with whitespace or control characters. Must not contain `\|` or `,`: these are the Config DB key separator and leaf-list separator respectively, so a name containing either cannot be referenced from **DHCP_SERVER_IPV4_BINDING**. | diff --git a/src/sonic-yang-models/tests/yang_model_tests/tests/dhcp_server_ipv4_match.json b/src/sonic-yang-models/tests/yang_model_tests/tests/dhcp_server_ipv4_match.json index 958773ea453..9a4460c3400 100644 --- a/src/sonic-yang-models/tests/yang_model_tests/tests/dhcp_server_ipv4_match.json +++ b/src/sonic-yang-models/tests/yang_model_tests/tests/dhcp_server_ipv4_match.json @@ -1,9 +1,9 @@ { "DHCP_SERVER_IPV4_MATCH_VALID_IP_BINDING": { - "desc": "Configure the MATCH tables with multiple conditions and bindings sharing a condition while the interface remains in PORT mode." + "desc": "Configure MATCH mode with multiple conditions and bindings sharing a condition." }, "DHCP_SERVER_IPV4_MATCH_VALID_RANGE_BINDING": { - "desc": "Configure the MATCH tables with a condition bound to a named range while the interface remains in PORT mode." + "desc": "Configure MATCH mode with a condition bound to a named range." }, "DHCP_SERVER_IPV4_MATCH_MAX_LENGTH_BOUNDARIES": { "desc": "Accept 255-character match names, match values, and binding names." diff --git a/src/sonic-yang-models/tests/yang_model_tests/tests_config/dhcp_server_ipv4_match.json b/src/sonic-yang-models/tests/yang_model_tests/tests_config/dhcp_server_ipv4_match.json index 16472a42c51..ce24cca7e1a 100644 --- a/src/sonic-yang-models/tests/yang_model_tests/tests_config/dhcp_server_ipv4_match.json +++ b/src/sonic-yang-models/tests/yang_model_tests/tests_config/dhcp_server_ipv4_match.json @@ -5,7 +5,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -80,7 +80,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -130,7 +130,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -258,7 +258,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -285,7 +285,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -324,7 +324,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -363,7 +363,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -416,7 +416,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -452,7 +452,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -502,7 +502,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -541,7 +541,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -580,7 +580,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -619,7 +619,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -663,7 +663,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -707,7 +707,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -732,7 +732,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -776,7 +776,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -820,7 +820,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -874,7 +874,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, @@ -918,7 +918,7 @@ "DHCP_SERVER_IPV4_LIST": [ { "name": "Vlan1000", - "mode": "PORT", + "mode": "MATCH", "gateway": "192.0.2.1", "netmask": "255.255.255.0", "lease_time": 900, diff --git a/src/sonic-yang-models/yang-models/sonic-dhcp-server-ipv4.yang b/src/sonic-yang-models/yang-models/sonic-dhcp-server-ipv4.yang index f17a49a2496..7338097fd86 100644 --- a/src/sonic-yang-models/yang-models/sonic-dhcp-server-ipv4.yang +++ b/src/sonic-yang-models/yang-models/sonic-dhcp-server-ipv4.yang @@ -86,6 +86,7 @@ module sonic-dhcp-server-ipv4 { mandatory true; type enumeration { enum PORT; + enum MATCH; } } From 812d41c2a62213023f7617fb84949085a0f4b41b Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Wed, 28 Oct 2026 03:40:32 +0000 Subject: [PATCH 2/9] Addressing review comments by Copilot AI Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 181 +++++++++++++++- .../cli/config/plugins/dhcp_server.py | 119 ++++++++--- .../dhcp_utilities/dhcpservd/dhcp_cfggen.py | 70 +++--- .../tests/test_dhcp_match_cfggen.py | 202 ++++++++++++++++-- 4 files changed, 489 insertions(+), 83 deletions(-) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index f5dbf165c37..7e2d1415944 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -15,6 +15,97 @@ RANGE_COMMAND = IPV4_COMMAND.commands["range"] +@pytest.fixture +def prefix_db(mock_db): + for table in ("DHCP_SERVER_IPV4_BINDING", "DHCP_SERVER_IPV4_PORT"): + for key in mock_db.keys("CONFIG_DB", table + "|Vlan100|*"): + mock_db.delete("CONFIG_DB", key) + mock_db.hmset("CONFIG_DB", "VLAN_INTERFACE|Vlan100|100.1.2.1/24", {}) + return mock_db + + +@pytest.mark.parametrize("mode", ["PORT", "MATCH"]) +@pytest.mark.parametrize("operation", [ + "add", "add-range", "same-entry", "binding-update", "range-update", "enable", "mode-update" +]) +def test_multiple_served_prefixes_rejected_only_for_match(prefix_db, mode, operation): + db = prefix_db + table = "DHCP_SERVER_IPV4_BINDING" if mode == "MATCH" else "DHCP_SERVER_IPV4_PORT" + first = "first" if mode == "MATCH" else "Ethernet2" + second = "second" if mode == "MATCH" else "Ethernet4" + first_entry = {"ips@": "100.1.1.30"} + second_entry = {"ips@": "100.1.2.30"} + if mode == "MATCH": + first_entry["matches@"] = "vendor-a" + second_entry["matches@"] = "vendor-b" + db.hmset("CONFIG_DB", "{}|Vlan100|{}".format(table, first), first_entry) + db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", mode) + if operation in ("add", "add-range"): + command = BINDING_COMMAND.commands["add"] if mode == "MATCH" else IPV4_COMMAND.commands["bind"] + args = ["Vlan100", second] + args += ["--range=range5"] if operation == "add-range" else ["100.1.2.30"] + if mode == "MATCH": + args += ["--match=vendor-b"] + elif operation == "same-entry": + command = BINDING_COMMAND.commands["update"] if mode == "MATCH" else IPV4_COMMAND.commands["bind"] + args = ["Vlan100", first, "100.1.1.30,100.1.2.30"] + elif operation == "binding-update": + second_entry["ips@"] = "100.1.1.40" + db.hmset("CONFIG_DB", "{}|Vlan100|{}".format(table, second), second_entry) + command = BINDING_COMMAND.commands["update"] if mode == "MATCH" else IPV4_COMMAND.commands["bind"] + args = ["Vlan100", second, "100.1.2.30"] + elif operation == "range-update": + second_entry.pop("ips@") + second_entry["ranges@"] = "range3" + db.hmset("CONFIG_DB", "{}|Vlan100|{}".format(table, second), second_entry) + command = RANGE_COMMAND.commands["update"] + args = ["range3", "100.1.2.30"] + else: + db.hmset("CONFIG_DB", "{}|Vlan100|{}".format(table, second), second_entry) + if operation == "enable": + db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state", "disabled") + command, args = IPV4_COMMAND.commands["enable"], ["Vlan100"] + else: + db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "PORT" if mode == "MATCH" else "MATCH") + command, args = IPV4_COMMAND.commands["update"], ["Vlan100", "--mode=" + mode] + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + + result = invoke(db, command, args) + + if mode == "MATCH": + assert result.exit_code == 2, result.output + assert "DHCP pools on Vlan100 cannot span multiple IPv4 prefixes" in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + else: + assert result.exit_code == 0, result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} != before + + +@pytest.mark.parametrize("mode", ["PORT", "MATCH"]) +@pytest.mark.parametrize("wide_prefix", [False, True]) +def test_single_served_prefix_allowed(prefix_db, mode, wide_prefix): + db = prefix_db + first_ip, second_ip = "100.1.1.30", "100.1.1.40" + if wide_prefix: + db.delete("CONFIG_DB", "VLAN_INTERFACE|Vlan100|100.1.1.1/24") + db.hmset("CONFIG_DB", "VLAN_INTERFACE|Vlan100|172.17.31.254/19", {}) + first_ip, second_ip = "172.17.0.1", "172.17.26.1" + db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", mode) + if mode == "MATCH": + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|first", + {"matches@": "vendor-a", "ips@": first_ip}) + command = BINDING_COMMAND.commands["add"] + args = ["Vlan100", "second", "--match=vendor-b", second_ip] + else: + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_PORT|Vlan100|Ethernet2", {"ips@": first_ip}) + command = IPV4_COMMAND.commands["bind"] + args = ["Vlan100", "Ethernet4", second_ip] + + result = invoke(db, command, args) + + assert result.exit_code == 0, result.output + + def invoke(mock_db, command, args): db = clicommon.Db() db.db = mock_db @@ -62,9 +153,8 @@ def test_update_enabled_interface_to_match_mode_without_binding(self, mock_db): result = invoke(mock_db, IPV4_COMMAND.commands["update"], ["Vlan100", "--mode=MATCH"]) - assert result.exit_code == 2 - assert "requires at least one binding" in result.output - assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode") == "PORT" + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode") == "MATCH" def test_enable_match_interface_with_valid_bindings(self, mock_db): mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") @@ -80,9 +170,8 @@ def test_enable_match_interface_without_binding(self, mock_db): result = invoke(mock_db, IPV4_COMMAND.commands["enable"], ["Vlan300"]) - assert result.exit_code == 2 - assert "requires at least one binding" in result.output - assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan300", "state") == "disabled" + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan300", "state") == "enabled" def test_delete_interface_referenced_by_match_binding(self, mock_db): for key in list(mock_db.keys("CONFIG_DB", "DHCP_SERVER_IPV4_PORT|Vlan100|*")): @@ -338,8 +427,7 @@ def test_match_update_circuit_id_unknown_port(self, mock_db): def test_range_update_breaking_binding_rejected(self, mock_db): """range3 is bound by Vlan100/fallback; moving it off-subnet must be refused. - dhcp_cfggen aborts the whole Kea config when a pool falls outside the VLAN, - so this would take DHCP down for every interface, not just this one. + dhcp_cfggen would silently drop the binding's pool. """ result = invoke( mock_db, @@ -945,3 +1033,80 @@ def test_binding_update_rejected_leaves_config_unchanged(self, mock_db): assert result.exit_code == 2 assert dict(mock_db.get_all("CONFIG_DB", key)) == before + + @pytest.mark.parametrize("ip_list, exit_code", [ + ("100.1.1.20", 0), + ("100.1.1.21", 0), + ("100.1.1.20,100.1.1.21", 2), + ]) + def test_binding_add_pool_overlap(self, mock_db, ip_list, exit_code): + """maia-a owns 100.1.1.20; Kea can share an identical pool but not compile a partial overlap.""" + result = invoke( + mock_db, + BINDING_COMMAND.commands["add"], + ["Vlan100", "maia-b", "--match", "port-etp2,vendor-b", ip_list], + ) + + assert result.exit_code == exit_code, result.output + if exit_code: + assert "Bindings maia-a and maia-b have partially overlapping pools on Vlan100" in result.output + assert mock_db.exists("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-b") == (exit_code == 0) + + def test_range_update_causing_partial_pool_overlap_rejected(self, mock_db): + result = invoke(mock_db, RANGE_COMMAND.commands["update"], ["range3", "100.1.1.10", "100.1.1.20"]) + + assert result.exit_code == 2 + assert "Bindings fallback and maia-a have partially overlapping pools on Vlan100" in result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3", "range@") == "100.1.1.10" + + def test_enable_match_interface_with_partial_pool_overlap_rejected(self, mock_db): + mock_db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-b", + {"matches@": "port-etp2,vendor-b", "ips@": "100.1.1.20,100.1.1.21"}) + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state", "disabled") + + result = invoke(mock_db, IPV4_COMMAND.commands["enable"], ["Vlan100"]) + + assert result.exit_code == 2 + assert "partially overlapping pools" in result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state") == "disabled" + + @pytest.mark.parametrize("state", ["enabled", "disabled"]) + def test_binding_del_final_binding(self, mock_db, state): + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state", state) + mock_db.delete("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|fallback") + + result = invoke(mock_db, BINDING_COMMAND.commands["del"], ["Vlan100", "maia-a"]) + + assert result.exit_code == 0, result.output + assert not mock_db.keys("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|*") + + @pytest.mark.parametrize("command,args", [ + (BINDING_COMMAND.commands["add"], ["Vlan100", "vendor-b", "--match=vendor-b", "100.1.1.40"]), + (BINDING_COMMAND.commands["update"], ["Vlan100", "maia-a", "--match=vendor-a"]), + (IPV4_COMMAND.commands["enable"], ["Vlan100"]), + (IPV4_COMMAND.commands["update"], ["Vlan100", "--mode=MATCH"]), + (MATCH_COMMAND.commands["update"], ["vendor-a", "--value=MAIA-C"]), + (RANGE_COMMAND.commands["update"], ["range3", "100.1.1.50"]), + (BINDING_COMMAND.commands["del"], ["Vlan100", "fallback"]), + ]) + def test_stale_binding_does_not_block_other_changes(self, mock_db, command, args): + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state", "disabled") + # fallback goes stale when its port leaves the VLAN, as dhcp_cfggen then skips it + mock_db.delete("CONFIG_DB", "VLAN_MEMBER|Vlan100|Ethernet2") + mock_db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-a", + {"matches@": "vendor-a", "ips@": "100.1.1.20"}) + + result = invoke(mock_db, command, args) + + assert result.exit_code == 0, result.output + + def test_stale_binding_cannot_be_rewritten_invalid(self, mock_db): + mock_db.delete("CONFIG_DB", "VLAN_MEMBER|Vlan100|Ethernet2") + + result = invoke(mock_db, BINDING_COMMAND.commands["update"], ["Vlan100", "fallback", "--range=range3"]) + + assert result.exit_code == 2 + assert "is not a member of vlan Vlan100" in result.output diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 46a58eb9a24..0091c410862 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -98,15 +98,28 @@ def get_vlan_subnets(dbconn, dhcp_interface): return subnets +def add_pool_interval(intervals, subnets, start, end): + """Record an address interval under the first VLAN subnet that contains it.""" + start = ipaddress.ip_address(start) + end = ipaddress.ip_address(end) + subnet = next((subnet for subnet in subnets if start in subnet and end in subnet), None) + if subnet is not None: + intervals.setdefault(subnet, []).append((int(start), int(end))) + return subnet is not None + + def validate_ip_pool(ips, subnets, dhcp_interface): + intervals = {} for ip in ips: if not validate_str_type("ipv4-address", ip): click.get_current_context().fail("Illegal IP address {}".format(ip)) - if not any(ipaddress.ip_address(ip) in subnet for subnet in subnets): + if not add_pool_interval(intervals, subnets, ip, ip): click.get_current_context().fail("IP {} is not in any subnet of vlan {}".format(ip, dhcp_interface)) + return intervals def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides=None): + intervals = {} for range_name in ranges: key = "DHCP_SERVER_IPV4_RANGE|" + range_name if range_overrides and range_name in range_overrides: @@ -124,10 +137,10 @@ def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides click.get_current_context().fail("Range {} has an invalid IPv4 address".format(range_name)) if count_ipv4(ip_start, ip_end) < 1: click.get_current_context().fail("Range {} has an invalid address order".format(range_name)) - if not any(ipaddress.ip_address(ip_start) in subnet and ipaddress.ip_address(ip_end) in subnet - for subnet in subnets): + if not add_pool_interval(intervals, subnets, ip_start, ip_end): click.get_current_context().fail( "Range {} is not in any subnet of vlan {}".format(range_name, dhcp_interface)) + return intervals def get_match_entry(dbconn, match_name, match_overrides=None): @@ -140,8 +153,8 @@ def get_match_entry(dbconn, match_name, match_overrides=None): entry = dbconn.get_all("CONFIG_DB", key) if entry.get("type") not in SUPPORTED_MATCH_TYPE: click.get_current_context().fail("Match {} has unsupported type {}".format(match_name, entry.get("type", ""))) - if not entry.get("value") or len(entry["value"]) > 255: - click.get_current_context().fail("Match {} has an invalid value".format(match_name)) + if not entry.get("value") or len(entry["value"].encode("utf-8")) > 255: + click.get_current_context().fail("Match {} has an invalid value or exceeds 255 UTF-8 bytes".format(match_name)) return entry @@ -206,19 +219,51 @@ def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_ov subnets = get_vlan_subnets(dbconn, dhcp_interface) if has_ips: - validate_ip_pool(split_csv(entry["ips@"], "IP list"), subnets, dhcp_interface) + intervals = validate_ip_pool(split_csv(entry["ips@"], "IP list"), subnets, dhcp_interface) else: - validate_range_pool(dbconn, split_csv(entry["ranges@"], "Range list"), subnets, dhcp_interface, - range_overrides) - return conditions + intervals = validate_range_pool(dbconn, split_csv(entry["ranges@"], "Range list"), subnets, + dhcp_interface, range_overrides) + return conditions, {subnet: merge_pool_intervals(pool) for subnet, pool in intervals.items()} + + +def merge_pool_intervals(intervals): + """Merge overlapping or adjacent intervals the same way dhcp_cfggen builds Kea pools.""" + merged = [] + for start, end in sorted(intervals): + if merged and start <= merged[-1][1] + 1: + merged[-1] = (merged[-1][0], max(merged[-1][1], end)) + else: + merged.append((start, end)) + return merged + + +def pools_partially_overlap(first, second): + """Identical pools share one Kea pool; any other shared address cannot be compiled.""" + for subnet in set(first) & set(second): + if first[subnet] != second[subnet] and any( + first_start <= second_end and second_start <= first_end + for first_start, first_end in first[subnet] + for second_start, second_end in second[subnet]): + return True + return False def predicates_overlap(first, second): return all(match_type not in second or second[match_type] == value for match_type, value in first.items()) +def validate_single_prefix(dhcp_interface, prefixes): + prefixes = sorted(set(prefixes), key=str) + if len(prefixes) > 1: + click.get_current_context().fail( + "DHCP pools on {} cannot span multiple IPv4 prefixes: {}".format( + dhcp_interface, ", ".join(str(prefix) for prefix in prefixes) + ) + ) + + def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrides=None, - range_overrides=None, port_alias_map=None, require_binding=False): + range_overrides=None, port_alias_map=None): bindings = {} prefix = "DHCP_SERVER_IPV4_BINDING|{}|".format(dhcp_interface) for key in dbconn.keys("CONFIG_DB", prefix + "*"): @@ -227,16 +272,30 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid bindings[candidate[0]] = candidate[1] if port_alias_map is None: port_alias_map = {} - if require_binding and not bindings: - click.get_current_context().fail("MATCH mode requires at least one binding on {}".format(dhcp_interface)) predicates = {} + pools = {} for binding_name in sorted(bindings): - predicates[binding_name] = validate_binding_entry( - dbconn, dhcp_interface, binding_name, bindings[binding_name], match_overrides, - range_overrides, port_alias_map - ) - + try: + predicates[binding_name], pools[binding_name] = validate_binding_entry( + dbconn, dhcp_interface, binding_name, bindings[binding_name], match_overrides, + range_overrides, port_alias_map + ) + except click.UsageError: + if candidate and binding_name == candidate[0]: + raise + # dhcp_cfggen skips a binding that is already invalid (for example after + # its port left the VLAN), so it must not block unrelated changes. Only + # reject when this change is what breaks the binding. + if match_overrides or range_overrides: + try: + validate_binding_entry(dbconn, dhcp_interface, binding_name, bindings[binding_name], + port_alias_map=port_alias_map) + except click.UsageError: + continue + raise + + validate_single_prefix(dhcp_interface, (subnet for pool in pools.values() for subnet in pool)) binding_names = sorted(predicates) for index, first_name in enumerate(binding_names): for second_name in binding_names[index + 1:]: @@ -248,20 +307,23 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid first_name, second_name, dhcp_interface ) ) + if pools_partially_overlap(pools[first_name], pools[second_name]): + click.get_current_context().fail( + "Bindings {} and {} have partially overlapping pools on {}".format( + first_name, second_name, dhcp_interface + ) + ) def validate_range_update(dbconn, range_name, updated_value): """Re-validate every binding that references a range before its endpoints move. A binding's pool is checked against the VLAN subnet when the binding itself is - written, but the range it names can be edited afterwards. dhcp_cfggen aborts - generation of the entire Kea config - not just the offending binding - when a - pool falls outside the VLAN, so an unchecked range update can take DHCP down - for every interface on the box, not only this one. - - DHCP_SERVER_IPV4_PORT entries can also reference a range and are deliberately - not covered here: they are validated nowhere today, so guarding them would - change behaviour that predates this series and belongs in its own change. + written, but the range it names can be edited afterwards. dhcp_cfggen drops a + pool that falls outside the VLAN, so an unchecked range update would silently + stop serving the binding. + + PORT entries retain their existing validation behavior. """ affected_vlans = set() for key in dbconn.keys("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|*"): @@ -292,7 +354,6 @@ def validate_match_update(dbconn, match_name, updated_entry, port_alias_map=None dhcp_interface, match_overrides={match_name: updated_entry}, port_alias_map=port_alias_map, - require_binding=True, ) @@ -311,7 +372,7 @@ def dhcp_server(db): @dhcp_server.group(cls=clicommon.AliasedGroup, name="ipv4") def dhcp_server_ipv4(): - """Show ipv4 related dhcp_server info""" + """Configure IPv4 DHCP; MATCH pools on each interface must use one IPv4 prefix.""" pass @@ -393,7 +454,7 @@ def dhcp_server_ipv4_update(db, mode, lease_time, dup_gw_nm, gateway, netmask, d if mode not in SUPPORTED_MODE: ctx.fail("Only modes {} are supported".format(", ".join(SUPPORTED_MODE))) if mode == "MATCH" and dbconn.get("CONFIG_DB", interface_key, "state") == "enabled": - validate_vlan_bindings(dbconn, dhcp_interface, require_binding=True) + validate_vlan_bindings(dbconn, dhcp_interface) updates["mode"] = mode if lease_time: if not validate_str_type("uint32", lease_time): @@ -430,7 +491,7 @@ def dhcp_server_ipv4_enable(db, dhcp_interface): key = "DHCP_SERVER_IPV4|" + dhcp_interface if dbconn.exists("CONFIG_DB", key): if dbconn.get("CONFIG_DB", key, "mode") == "MATCH": - validate_vlan_bindings(dbconn, dhcp_interface, require_binding=True) + validate_vlan_bindings(dbconn, dhcp_interface) dbconn.set("CONFIG_DB", key, "state", "enabled") else: ctx.fail("Failed to enable, dhcp interface {} does not exist".format(dhcp_interface)) diff --git a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py index bdd9c4ad6ed..a0358992969 100755 --- a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py +++ b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py @@ -72,6 +72,8 @@ def generate(self): set of match conditions used by enabled MATCH bindings """ # Generate from running config_db + # PORT and PORTCHANNEL are not monitored, so refresh circuit ID names on every generation + self._parse_port_map_alias() # Get host name device_metadata = self.db_connector.get_config_db_table("DEVICE_METADATA") hostname = self._parse_hostname(device_metadata) @@ -311,7 +313,9 @@ def _construct_obj_for_template(self, dhcp_server_ipv4, port_ips, hostname, cust elif dhcp_config["mode"] == "MATCH": subscribe_table |= set(MATCH_MODE_CHECKER) if dhcp_interface_name not in match_pools: - raise ValueError("Cannot get DHCP MATCH binding config for {}".format(dhcp_interface_name)) + syslog.syslog(syslog.LOG_WARNING, "Cannot get DHCP MATCH binding config for {}" + .format(dhcp_interface_name)) + continue curr_options = {} dhcp_server_id_option = {} if "customized_options" in dhcp_config: @@ -331,6 +335,10 @@ def _construct_obj_for_template(self, dhcp_server_ipv4, port_ips, hostname, cust dhcp_server_id_option = current_option else: curr_options[option] = current_option + if len(match_pools[dhcp_interface_name]) > 1: + raise ValueError( + "DHCP MATCH pools on {} cannot span multiple IPv4 prefixes".format(dhcp_interface_name) + ) for dhcp_interface_ip, pools in match_pools[dhcp_interface_name].items(): current_server_id_option = dhcp_server_id_option if not current_server_id_option: @@ -607,12 +615,10 @@ def _parse_match_condition(self, match_name, match_ipv4, hostname, condition_cac resolved_value = value if match_type == "circuit_id": ports = sorted(port for port, alias in self.port_alias_map.items() if alias == value) - if not ports: - raise ValueError("Circuit ID value {} does not match any port alias, " - "aliasless port name or PortChannel name".format(value)) if len(ports) > 1: raise ValueError("Circuit ID value {} is ambiguous".format(value)) - port_name = ports[0] + # Like _parse_port, fall back to the value itself when no port or PortChannel carries it + port_name = ports[0] if ports else value resolved_value = "{}:{}".format(hostname, value) encoded_value = resolved_value.encode("utf-8") @@ -634,16 +640,14 @@ def _parse_match_condition(self, match_name, match_ipv4, hostname, condition_cac return condition def _find_match_subnet(self, dhcp_interface_name, dhcp_interfaces, start, end): - if dhcp_interface_name not in dhcp_interfaces: - raise ValueError("Interface {} has no IPv4 subnet".format(dhcp_interface_name)) matching_subnets = [ - interface for interface in dhcp_interfaces[dhcp_interface_name] + interface for interface in dhcp_interfaces.get(dhcp_interface_name, []) if start in interface["network"] and end in interface["network"] ] if not matching_subnets: - raise ValueError( - "Pool {}-{} is not in an IPv4 subnet of {}".format(start, end, dhcp_interface_name) - ) + syslog.syslog(syslog.LOG_WARNING, "Pool {}-{} of {} is not in an IPv4 subnet, skip".format( + start, end, dhcp_interface_name)) + return None if len(matching_subnets) > 1: raise ValueError( "Pool {}-{} matches multiple IPv4 subnets of {}".format(start, end, dhcp_interface_name) @@ -682,19 +686,21 @@ def _parse_binding_pools(self, dhcp_interface_name, binding_name, binding_config subnet = self._find_match_subnet( dhcp_interface_name, dhcp_interfaces, address, address ) - intervals_by_subnet.setdefault(subnet, []).append([address, address]) + if subnet is not None: + intervals_by_subnet.setdefault(subnet, []).append([address, address]) else: for range_name in values: used_ranges.add(range_name) if range_name not in ranges: - raise ValueError("Range {} referenced by {}|{} does not exist".format( - range_name, dhcp_interface_name, binding_name - )) + syslog.syslog(syslog.LOG_WARNING, "Range {} referenced by {}|{} is not in range table, skip" + .format(range_name, dhcp_interface_name, binding_name)) + continue start, end = ranges[range_name] subnet = self._find_match_subnet( dhcp_interface_name, dhcp_interfaces, start, end ) - intervals_by_subnet.setdefault(subnet, []).append([start, end]) + if subnet is not None: + intervals_by_subnet.setdefault(subnet, []).append([start, end]) for subnet, intervals in intervals_by_subnet.items(): intervals_by_subnet[subnet] = self._merge_match_intervals(intervals) @@ -737,7 +743,10 @@ def _parse_match_bindings(self, dhcp_server_ipv4, match_ipv4, binding_ipv4, dhcp for dhcp_interface_name in sorted(enabled_match_interfaces): interface_bindings = bindings_by_interface[dhcp_interface_name] if not interface_bindings: - raise ValueError("MATCH mode requires at least one binding on {}".format(dhcp_interface_name)) + continue + if dhcp_interface_name not in dhcp_interfaces: + syslog.syslog(syslog.LOG_WARNING, f"Interface {dhcp_interface_name} doesn't have IPv4 address") + continue normalized_bindings = [] for binding_name, binding_config in sorted(interface_bindings): @@ -751,8 +760,16 @@ def _parse_match_bindings(self, dhcp_server_ipv4, match_ipv4, binding_ipv4, dhcp dhcp_interface_name, binding_name )) + binding_key = "{}|{}".format(dhcp_interface_name, binding_name) + # Track references before skipping so restoring them triggers regeneration, as PORT mode does + used_matches.update(match_names) + used_ranges.update(self._normalize_list(binding_config.get("ranges"))) conditions = {} + skip_reason = None for match_name in match_names: + if match_name not in match_ipv4: + skip_reason = "match {} does not exist".format(match_name) + break condition = self._parse_match_condition( match_name, match_ipv4, hostname, condition_cache ) @@ -764,29 +781,32 @@ def _parse_match_bindings(self, dhcp_server_ipv4, match_ipv4, binding_ipv4, dhcp ) if condition["type"] == "circuit_id" and \ "{}|{}".format(dhcp_interface_name, condition["port"]) not in vlan_members: - raise ValueError( - "Circuit ID value {} is not a member of {}".format( - condition["value"], dhcp_interface_name - ) + skip_reason = "circuit ID value {} is not a member of {}".format( + condition["value"], dhcp_interface_name ) + break conditions[condition["type"]] = condition - used_matches.add(match_name) + if skip_reason: + syslog.syslog(syslog.LOG_WARNING, "Binding {}: {}, skip".format(binding_key, skip_reason)) + continue - intervals_by_subnet, binding_used_ranges = self._parse_binding_pools( + intervals_by_subnet, _ = self._parse_binding_pools( dhcp_interface_name, binding_name, binding_config, dhcp_interfaces, ranges ) - used_ranges |= binding_used_ranges + if not intervals_by_subnet: + syslog.syslog(syslog.LOG_WARNING, "Binding {} has no usable pool, skip".format(binding_key)) + continue raw_predicate = " and ".join( "({})".format(conditions[match_type]["atom"]) for match_type in SUPPORTED_MATCH_TYPES if match_type in conditions ) normalized_bindings.append({ "name": binding_name, - "key": "{}|{}".format(dhcp_interface_name, binding_name), + "key": binding_key, "conditions": conditions, "specificity": len(conditions), "raw_predicate": raw_predicate, diff --git a/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py index 60e8fe95776..4a1897ba804 100644 --- a/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py +++ b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py @@ -1,5 +1,6 @@ import ipaddress import json +import syslog from unittest.mock import patch import pytest @@ -44,6 +45,61 @@ def get_config_db_table(self, table_name): return self.tables.get(table_name, {}) +@pytest.mark.parametrize("mode", ["PORT", "MATCH"]) +@pytest.mark.parametrize("scenario", ["multiple-prefixes", "single-prefix", "wide-prefix", "different-vlans"]) +def test_generated_prefix_restriction_is_match_only(mode, scenario): + first_ip, second_ip = "192.168.10.100", "192.168.20.100" + addresses = {"Vlan1000|192.168.10.1/24": {}, "Vlan1000|192.168.20.1/24": {}} + second_vlan = "Vlan1000" + if scenario == "single-prefix": + second_ip = "192.168.10.101" + elif scenario == "wide-prefix": + first_ip, second_ip = "172.17.0.1", "172.17.26.1" + addresses = {"Vlan1000|172.17.31.254/19": {}} + elif scenario == "different-vlans": + second_vlan = "Vlan2000" + addresses = {"Vlan1000|192.168.10.1/24": {}, "Vlan2000|192.168.20.1/24": {}} + tables = { + "DEVICE_METADATA": {"localhost": {"hostname": "sonic-host"}}, + "PORT": {"Ethernet0": {"alias": "etp1"}, "Ethernet4": {"alias": "etp2"}}, + "VLAN_INTERFACE": addresses, + "VLAN_MEMBER": {"Vlan1000|Ethernet0": {}, second_vlan + "|Ethernet4": {}}, + "DHCP_SERVER_IPV4": { + vlan: {"mode": mode, "state": "enabled", "lease_time": "900"} + for vlan in ("Vlan1000", second_vlan) + }, + "DHCP_SERVER_IPV4_PORT": { + "Vlan1000|Ethernet0": {"ips": [first_ip]}, + second_vlan + "|Ethernet4": {"ips": [second_ip]} + }, + "DHCP_SERVER_IPV4_MATCH": { + "a": {"type": "option60", "value": "Vendor-A"}, + "b": {"type": "option60", "value": "Vendor-B"} + }, + "DHCP_SERVER_IPV4_BINDING": { + "Vlan1000|a": {"matches": ["a"], "ips": [first_ip]}, + second_vlan + "|b": {"matches": ["b"], "ips": [second_ip]} + } + } + generator = DhcpServCfgGenerator( + DictConnector(tables), "/usr/local/lib/kea/hooks/libdhcp_run_script.so", + kea_conf_template_path="../../dockers/docker-dhcp-server/kea-dhcp4.conf.j2" + ) + if scenario == "multiple-prefixes" and mode == "MATCH": + with pytest.raises(ValueError, match="DHCP MATCH pools on Vlan1000 cannot span multiple IPv4 prefixes"): + generator.generate() + else: + config = json.loads(generator.generate()[0]) + subnets = config["Dhcp4"]["subnet4"] + assert len(subnets) == (2 if scenario in ("different-vlans", "multiple-prefixes") else 1) + if scenario == "multiple-prefixes": + # Preserve the existing PORT output, including its duplicate-ID limitation. + assert [subnet["id"] for subnet in subnets] == [1000, 1000] + else: + assert len({subnet["id"] for subnet in subnets}) == len(subnets) + assert sum(len(subnet["pools"]) for subnet in subnets) == 2 + + def create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template): with patch.object(DhcpServCfgGenerator, "_parse_port_map_alias"): generator = DhcpServCfgGenerator( @@ -177,25 +233,12 @@ def test_match_compilation_is_deterministic(mock_swsscommon_dbconnector_init, mo @pytest.mark.parametrize("bindings,error", [ - ({}, "requires at least one binding"), - ({ - "Vlan1000|missing": { - "matches": ["missing-match"], - "ips": ["192.168.0.20"] - } - }, "does not exist"), ({ "Vlan1000|duplicate-type": { "matches": ["vendor-a", "vendor-b"], "ips": ["192.168.0.20"] } - }, "multiple matches of type option60"), - ({ - "Vlan1000|outside": { - "matches": ["vendor-a"], - "ips": ["192.168.1.20"] - } - }, "is not in an IPv4 subnet") + }, "multiple matches of type option60") ]) def test_invalid_match_bindings_are_rejected(mock_swsscommon_dbconnector_init, mock_get_render_template, bindings, error): @@ -243,17 +286,68 @@ def test_partial_pool_overlap_is_rejected(mock_swsscommon_dbconnector_init, mock parse_bindings(generator, bindings, ranges=ranges) -def test_circuit_id_must_be_vlan_member(mock_swsscommon_dbconnector_init, mock_get_render_template): +@pytest.mark.parametrize("binding,members,warning", [ + ({"matches": ["missing-match"], "ips": ["192.168.0.20"]}, VLAN_MEMBERS, + "Binding Vlan1000|stale: match missing-match does not exist, skip"), + ({"matches": ["port-etp7"], "ips": ["192.168.0.20"]}, {"Vlan1000|Ethernet28"}, + "Binding Vlan1000|stale: circuit ID value etp7 is not a member of Vlan1000, skip"), + ({"matches": ["vendor-a"], "ips": ["192.168.1.20"]}, VLAN_MEMBERS, + "Binding Vlan1000|stale has no usable pool, skip"), + ({"matches": ["vendor-a"], "ranges": ["missing-range"]}, VLAN_MEMBERS, + "Binding Vlan1000|stale has no usable pool, skip") +]) +def test_binding_with_missing_dependency_is_skipped(mock_swsscommon_dbconnector_init, mock_get_render_template, + binding, members, warning): generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) bindings = { - "Vlan1000|port-only": { - "matches": ["port-etp7"], - "ips": ["192.168.0.20"] - } + "Vlan1000|stale": binding, + "Vlan1000|healthy": {"matches": ["vendor-b"], "ips": ["192.168.0.40"]} } - with pytest.raises(ValueError, match="is not a member"): - parse_bindings(generator, bindings, members={"Vlan1000|Ethernet28"}) + with patch("syslog.syslog") as mock_syslog: + pools, _, used_ranges, used_matches = parse_bindings(generator, bindings, members=members) + + assert [pool["range"] for pool in pools["Vlan1000"]["192.168.0.1/24"]] == ["192.168.0.40 - 192.168.0.40"] + mock_syslog.assert_any_call(syslog.LOG_WARNING, warning) + # Restoring the missing match or range must trigger regeneration + assert set(binding["matches"]) <= used_matches + assert set(binding.get("ranges", [])) <= used_ranges + + +def test_missing_range_drops_only_that_pool(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = { + "Vlan1000|vendor-a": {"matches": ["vendor-a"], "ranges": ["fallback-range", "missing-range"]} + } + + with patch("syslog.syslog") as mock_syslog: + pools, _, _, _ = parse_bindings(generator, bindings) + + assert [pool["range"] for pool in pools["Vlan1000"]["192.168.0.1/24"]] == ["192.168.0.30 - 192.168.0.30"] + mock_syslog.assert_any_call( + syslog.LOG_WARNING, "Range missing-range referenced by Vlan1000|vendor-a is not in range table, skip") + + +def test_deleted_portchannel_still_vlan_member_is_served(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + matches = {"pc5": {"type": "circuit_id", "value": "PortChannel5"}} + bindings = {"Vlan1000|pc5": {"matches": ["pc5"], "ips": ["192.168.0.50"]}} + + pools, classes, _, _ = parse_bindings(generator, bindings, matches=matches, members={"Vlan1000|PortChannel5"}) + + assert [pool["range"] for pool in pools["Vlan1000"]["192.168.0.1/24"]] == ["192.168.0.50 - 192.168.0.50"] + assert "sonic-host:PortChannel5".encode("utf-8").hex() in classes[0]["condition"] + + +def test_match_interface_without_ipv4_is_skipped(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + bindings = {"Vlan1000|vendor-a": {"matches": ["vendor-a"], "ips": ["192.168.0.20"]}} + + with patch("syslog.syslog") as mock_syslog: + pools, _, _, _ = parse_bindings(generator, bindings, interfaces={}) + + assert pools == {} + mock_syslog.assert_any_call(syslog.LOG_WARNING, "Interface Vlan1000 doesn't have IPv4 address") def test_match_value_byte_limit_is_enforced(mock_swsscommon_dbconnector_init, mock_get_render_template): @@ -433,3 +527,69 @@ def test_generate_match_config_and_snapshots(): assert enabled_port_interfaces == set() assert enabled_match_interfaces == {"Vlan1000"} assert used_matches == {"port-etp7", "vendor-a"} + + +@pytest.mark.parametrize("mode,warning", [ + ("PORT", "Cannot get DHCP port config for Vlan2000"), + ("MATCH", "Cannot get DHCP MATCH binding config for Vlan2000") +]) +def test_enabled_interface_without_pool_config_is_skipped(mode, warning): + tables = { + "DEVICE_METADATA": {"localhost": {"hostname": "sonic-host"}}, + "VLAN_INTERFACE": { + "Vlan1000": {}, + "Vlan1000|192.168.0.1/24": {}, + "Vlan2000": {}, + "Vlan2000|192.168.1.1/24": {} + }, + "VLAN_MEMBER": {"Vlan1000|Ethernet24": {}}, + "PORT": {"Ethernet24": {"alias": "etp7"}}, + "DHCP_SERVER_IPV4": { + "Vlan1000": {"lease_time": "900", "mode": "MATCH", "state": "enabled"}, + "Vlan2000": {"lease_time": "900", "mode": mode, "state": "enabled"} + }, + "DHCP_SERVER_IPV4_MATCH": MATCHES, + "DHCP_SERVER_IPV4_BINDING": { + "Vlan1000|vendor-a": {"matches": ["vendor-a"], "ips": ["192.168.0.20"]} + } + } + generator = DhcpServCfgGenerator( + DictConnector(tables), + "/usr/local/lib/kea/hooks/libdhcp_run_script.so", + kea_conf_template_path="tests/test_data/kea-dhcp4.conf.j2" + ) + + with patch("syslog.syslog") as mock_syslog: + config, _, enabled_interfaces, _, checkers, enabled_port_interfaces, enabled_match_interfaces, _ = \ + generator.generate() + + assert [subnet["subnet"] for subnet in json.loads(config)["Dhcp4"]["subnet4"]] == ["192.168.0.0/24"] + assert enabled_interfaces == {"Vlan1000", "Vlan2000"} + assert "Vlan2000" in (enabled_port_interfaces if mode == "PORT" else enabled_match_interfaces) + assert set(PORT_MODE_CHECKER if mode == "PORT" else MATCH_MODE_CHECKER) <= checkers + mock_syslog.assert_any_call(syslog.LOG_WARNING, warning) + + +def test_portchannel_added_after_start_is_resolved(): + tables = { + "DEVICE_METADATA": {"localhost": {"hostname": "sonic-host"}}, + "VLAN_INTERFACE": {"Vlan1000": {}, "Vlan1000|192.168.0.1/24": {}}, + "VLAN_MEMBER": {}, + "PORT": {}, + "PORTCHANNEL": {}, + "DHCP_SERVER_IPV4": {"Vlan1000": {"lease_time": "900", "mode": "MATCH", "state": "enabled"}}, + "DHCP_SERVER_IPV4_MATCH": {"pc5": {"type": "circuit_id", "value": "PortChannel5"}}, + "DHCP_SERVER_IPV4_BINDING": {} + } + generator = DhcpServCfgGenerator( + DictConnector(tables), + "/usr/local/lib/kea/hooks/libdhcp_run_script.so", + kea_conf_template_path="tests/test_data/kea-dhcp4.conf.j2" + ) + tables["PORTCHANNEL"]["PortChannel5"] = {} + tables["VLAN_MEMBER"]["Vlan1000|PortChannel5"] = {} + tables["DHCP_SERVER_IPV4_BINDING"]["Vlan1000|pc5"] = {"matches": ["pc5"], "ips": ["192.168.0.50"]} + + _, _, _, _, _, _, _, used_matches = generator.generate() + + assert used_matches == {"pc5"} From 566f6ecd6d82fe7fc138a5159fb4b79542097525 Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Fri, 30 Oct 2026 05:22:36 +0000 Subject: [PATCH 3/9] Addressing review comments Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 97 +++++++++++++++++++ .../cli/config/plugins/dhcp_server.py | 19 ++-- .../dhcp_utilities/dhcpservd/dhcp_cfggen.py | 4 +- .../dhcp_utilities/dhcpservd/dhcpservd.py | 2 +- .../tests/test_dhcp_match_cfggen.py | 37 ++++++- 5 files changed, 148 insertions(+), 11 deletions(-) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index 7e2d1415944..b617df30f0e 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -112,6 +112,103 @@ def invoke(mock_db, command, args): return CliRunner().invoke(command, args, obj=db) +@pytest.fixture +def binding_with_deleted_range(prefix_db): + db = prefix_db + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3", {"range@": "100.1.1.10,100.1.1.12"}) + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|surviving", + {"matches@": "vendor-a", "ranges@": "range1,range3"}) + result = invoke(db, RANGE_COMMAND.commands["del"], ["range1", "--force"]) + assert result.exit_code == 0, result.output + return db + + +@pytest.mark.parametrize("operation", [ + "add", "binding-update", "match-update", "range-update", "enable", "mode-update" +]) +@pytest.mark.parametrize("conflict", ["equal-specificity", "partial-pool"]) +def test_surviving_ranges_participate_in_conflict_checks(binding_with_deleted_range, operation, conflict): + db = binding_with_deleted_range + match = "vendor-a" if conflict == "equal-specificity" else "vendor-b" + ips = "100.1.1.40" if conflict == "equal-specificity" else "100.1.1.11,100.1.1.13" + entry = {"matches@": match, "ips@": ips} + if operation == "add": + command = BINDING_COMMAND.commands["add"] + args = ["Vlan100", "other", "--match=" + match, ips] + else: + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|other", entry) + if operation == "binding-update": + db.set("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|other", "ips@", "100.1.1.50") + command, args = BINDING_COMMAND.commands["update"], ["Vlan100", "other", ips] + elif operation == "match-update": + db.set("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|other", "matches@", "vendor-b") + value = "MAIA-A" if conflict == "equal-specificity" else "MAIA-C" + command, args = MATCH_COMMAND.commands["update"], ["vendor-b", "--value=" + value] + elif operation == "range-update": + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|other-range", {"range@": "100.1.1.50"}) + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|other", + {"matches@": match, "ranges@": "other-range"}) + endpoints = ["100.1.1.40"] if conflict == "equal-specificity" else ["100.1.1.11", "100.1.1.13"] + command, args = RANGE_COMMAND.commands["update"], ["other-range"] + endpoints + elif operation == "enable": + db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") + db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "state", "disabled") + command, args = IPV4_COMMAND.commands["enable"], ["Vlan100"] + else: + command, args = IPV4_COMMAND.commands["update"], ["Vlan100", "--mode=MATCH"] + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + + result = invoke(db, command, args) + + assert result.exit_code == 2, result.output + error = "overlap with equal specificity" if conflict == "equal-specificity" else "partially overlapping pools" + assert error in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + + +@pytest.mark.parametrize("all_ranges_missing", [False, True]) +def test_deleted_ranges_allow_nonconflicting_changes(binding_with_deleted_range, all_ranges_missing): + db = binding_with_deleted_range + if all_ranges_missing: + db.delete("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3") + match = "vendor-a" if all_ranges_missing else "vendor-b" + + result = invoke(db, BINDING_COMMAND.commands["add"], ["Vlan100", "other", "--match=" + match, "100.1.1.40"]) + + assert result.exit_code == 0, result.output + + +@pytest.mark.parametrize("start,end,error", [ + ("100.1.1.40", "100.1.1.41", "partially overlapping pools"), + ("100.1.3.10", "100.1.3.11", "is not in any subnet"), +]) +def test_surviving_range_update_remains_guarded(binding_with_deleted_range, start, end, error): + db = binding_with_deleted_range + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|other", + {"matches@": "vendor-b", "ips@": "100.1.1.40"}) + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + + result = invoke(db, RANGE_COMMAND.commands["update"], ["range3", start, end]) + + assert result.exit_code == 2, result.output + assert error in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + + +@pytest.mark.parametrize("operation", ["add", "update"]) +def test_candidate_with_missing_range_remains_strict(binding_with_deleted_range, operation): + db = binding_with_deleted_range + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + args = ["Vlan100", "other", "--match=vendor-b", "--range=range1,range3"] if operation == "add" else [ + "Vlan100", "surviving", "--match=vendor-b"] + + result = invoke(db, BINDING_COMMAND.commands[operation], args) + + assert result.exit_code == 2, result.output + assert "Range range1 does not exist" in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + + @pytest.fixture def dhcp_vlan200(mock_db): mock_db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan200", diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 0091c410862..7742e6e7d55 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -118,7 +118,8 @@ def validate_ip_pool(ips, subnets, dhcp_interface): return intervals -def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides=None): +def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides=None, + allow_missing_ranges=False): intervals = {} for range_name in ranges: key = "DHCP_SERVER_IPV4_RANGE|" + range_name @@ -126,6 +127,8 @@ def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides range_value = range_overrides[range_name] else: if not dbconn.exists("CONFIG_DB", key): + if allow_missing_ranges: + continue click.get_current_context().fail("Range {} does not exist".format(range_name)) range_value = dbconn.get("CONFIG_DB", key, "range@") range_ips = range_value.split(",") if range_value else [] @@ -186,7 +189,7 @@ def resolve_port_alias(dbconn, alias, port_alias_map=None): def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_overrides=None, - range_overrides=None, port_alias_map=None): + range_overrides=None, port_alias_map=None, allow_missing_ranges=False): validate_key_name(binding_name, "Binding name", "|") if not dbconn.exists("CONFIG_DB", "DHCP_SERVER_IPV4|" + dhcp_interface): click.get_current_context().fail("Interface {} is not a valid dhcp interface".format(dhcp_interface)) @@ -222,7 +225,7 @@ def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_ov intervals = validate_ip_pool(split_csv(entry["ips@"], "IP list"), subnets, dhcp_interface) else: intervals = validate_range_pool(dbconn, split_csv(entry["ranges@"], "Range list"), subnets, - dhcp_interface, range_overrides) + dhcp_interface, range_overrides, allow_missing_ranges) return conditions, {subnet: merge_pool_intervals(pool) for subnet, pool in intervals.items()} @@ -277,10 +280,14 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid pools = {} for binding_name in sorted(bindings): try: - predicates[binding_name], pools[binding_name] = validate_binding_entry( + conditions, intervals = validate_binding_entry( dbconn, dhcp_interface, binding_name, bindings[binding_name], match_overrides, - range_overrides, port_alias_map + range_overrides, port_alias_map, + allow_missing_ranges=not (candidate and binding_name == candidate[0]) ) + # Existing bindings still serve their surviving ranges, as dhcp_cfggen does. + if intervals: + predicates[binding_name], pools[binding_name] = conditions, intervals except click.UsageError: if candidate and binding_name == candidate[0]: raise @@ -290,7 +297,7 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid if match_overrides or range_overrides: try: validate_binding_entry(dbconn, dhcp_interface, binding_name, bindings[binding_name], - port_alias_map=port_alias_map) + port_alias_map=port_alias_map, allow_missing_ranges=True) except click.UsageError: continue raise diff --git a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py index a0358992969..ae789cdaf07 100755 --- a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py +++ b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py @@ -52,7 +52,7 @@ def __init__(self, dhcp_db_connector, hook_lib_path, lease_path=DEFAULT_LEASE_PA self.lease_path = lease_path self.lease_update_script_path = lease_update_script_path self.hook_lib_path = hook_lib_path - # Read port alias map file, this file is render after container start, so it would not change any more + # Keep aliases at startup values until relay and server alias updates can be coordinated. self._parse_port_map_alias() # Get kea config template self._get_render_template(kea_conf_template_path) @@ -72,8 +72,6 @@ def generate(self): set of match conditions used by enabled MATCH bindings """ # Generate from running config_db - # PORT and PORTCHANNEL are not monitored, so refresh circuit ID names on every generation - self._parse_port_map_alias() # Get host name device_metadata = self.db_connector.get_config_db_table("DEVICE_METADATA") hostname = self._parse_hostname(device_metadata) diff --git a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py index 2c6286a2381..67e71f0915f 100644 --- a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py +++ b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py @@ -106,10 +106,10 @@ def dump_dhcp4_config(self): prefix=".{}.".format(os.path.basename(self.kea_dhcp4_config_path)), delete=False ) as candidate: + candidate_path = candidate.name candidate.write(kea_dhcp4_config) candidate.flush() os.fsync(candidate.fileno()) - candidate_path = candidate.name validation = subprocess.run( [self.kea_dhcp4_binary, "-t", candidate_path], diff --git a/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py index 4a1897ba804..b4bfa67ab1d 100644 --- a/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py +++ b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py @@ -570,6 +570,38 @@ def test_enabled_interface_without_pool_config_is_skipped(mode, warning): mock_syslog.assert_any_call(syslog.LOG_WARNING, warning) +@pytest.mark.parametrize("mode", ["PORT", "MATCH"]) +def test_alias_change_keeps_startup_circuit_id_after_pool_update(mode): + tables = { + "DEVICE_METADATA": {"localhost": {"hostname": "sonic-host"}}, + "PORT": {"Ethernet24": {"alias": "etp7"}}, + "VLAN_INTERFACE": {"Vlan1000|192.168.0.1/24": {}}, + "VLAN_MEMBER": {"Vlan1000|Ethernet24": {}}, + "DHCP_SERVER_IPV4": {"Vlan1000": {"lease_time": "900", "mode": mode, "state": "enabled"}}, + "DHCP_SERVER_IPV4_PORT": {"Vlan1000|Ethernet24": {"ranges": ["pool"]}}, + "DHCP_SERVER_IPV4_MATCH": {"port": {"type": "circuit_id", "value": "etp7"}}, + "DHCP_SERVER_IPV4_BINDING": {"Vlan1000|port": {"matches": ["port"], "ranges": ["pool"]}}, + "DHCP_SERVER_IPV4_RANGE": {"pool": {"range": ["192.168.0.50", "192.168.0.51"]}} + } + generator = DhcpServCfgGenerator( + DictConnector(tables), + "/usr/local/lib/kea/hooks/libdhcp_run_script.so", + kea_conf_template_path="tests/test_data/kea-dhcp4.conf.j2" + ) + before = json.loads(generator.generate()[0])["Dhcp4"] + tables["PORT"]["Ethernet24"]["alias"] = "newalias" + tables["DHCP_SERVER_IPV4_RANGE"]["pool"]["range"] = ["192.168.0.50", "192.168.0.52"] + + after = json.loads(generator.generate()[0])["Dhcp4"] + + assert before["client-classes"] + assert [c["test"] for c in after["client-classes"]] == [c["test"] for c in before["client-classes"]] + pools = after["subnet4"][0]["pools"] + assert len(pools) == 1 + assert pools[0]["pool"] == "192.168.0.50 - 192.168.0.52" + assert pools[0]["client-class"] == after["client-classes"][0]["name"] + + def test_portchannel_added_after_start_is_resolved(): tables = { "DEVICE_METADATA": {"localhost": {"hostname": "sonic-host"}}, @@ -590,6 +622,9 @@ def test_portchannel_added_after_start_is_resolved(): tables["VLAN_MEMBER"]["Vlan1000|PortChannel5"] = {} tables["DHCP_SERVER_IPV4_BINDING"]["Vlan1000|pc5"] = {"matches": ["pc5"], "ips": ["192.168.0.50"]} - _, _, _, _, _, _, _, used_matches = generator.generate() + config, _, _, _, _, _, _, used_matches = generator.generate() assert used_matches == {"pc5"} + parsed = json.loads(config)["Dhcp4"] + assert parsed["subnet4"][0]["pools"][0]["pool"] == "192.168.0.50 - 192.168.0.50" + assert "sonic-host:PortChannel5".encode("utf-8").hex() in parsed["client-classes"][0]["test"] From c78343ce3ef0a0b428f7fcdec2632e769f5d94dd Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Mon, 2 Nov 2026 04:07:44 +0000 Subject: [PATCH 4/9] Addressing review comment by Copilot AI about shrinking subnet Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 106 ++++++++++++++++-- .../cli/config/plugins/dhcp_server.py | 27 +++-- 2 files changed, 111 insertions(+), 22 deletions(-) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index b617df30f0e..7f13a4c8ea6 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -113,22 +113,34 @@ def invoke(mock_db, command, args): @pytest.fixture -def binding_with_deleted_range(prefix_db): +def binding_with_surviving_pools(prefix_db, request): db = prefix_db db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3", {"range@": "100.1.1.10,100.1.1.12"}) db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|surviving", {"matches@": "vendor-a", "ranges@": "range1,range3"}) - result = invoke(db, RANGE_COMMAND.commands["del"], ["range1", "--force"]) - assert result.exit_code == 0, result.output + pool_state = getattr(request, "param", "deleted-range") + if pool_state == "deleted-range": + result = invoke(db, RANGE_COMMAND.commands["del"], ["range1", "--force"]) + assert result.exit_code == 0, result.output + else: + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range1", {"range@": "100.1.1.120,100.1.1.140"}) + if pool_state == "shrunk-ips": + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|surviving", + {"matches@": "vendor-a", "ips@": "100.1.1.10,100.1.1.11,100.1.1.12,100.1.1.200"}) + db.delete("CONFIG_DB", "VLAN_INTERFACE|Vlan100|100.1.1.1/24") + db.hmset("CONFIG_DB", "VLAN_INTERFACE|Vlan100|100.1.1.1/25", {}) return db +@pytest.mark.parametrize("binding_with_surviving_pools", [ + "deleted-range", "shrunk-ips", "shrunk-ranges" +], indirect=True) @pytest.mark.parametrize("operation", [ "add", "binding-update", "match-update", "range-update", "enable", "mode-update" ]) @pytest.mark.parametrize("conflict", ["equal-specificity", "partial-pool"]) -def test_surviving_ranges_participate_in_conflict_checks(binding_with_deleted_range, operation, conflict): - db = binding_with_deleted_range +def test_surviving_pools_participate_in_conflict_checks(binding_with_surviving_pools, operation, conflict): + db = binding_with_surviving_pools match = "vendor-a" if conflict == "equal-specificity" else "vendor-b" ips = "100.1.1.40" if conflict == "equal-specificity" else "100.1.1.11,100.1.1.13" entry = {"matches@": match, "ips@": ips} @@ -167,8 +179,8 @@ def test_surviving_ranges_participate_in_conflict_checks(binding_with_deleted_ra @pytest.mark.parametrize("all_ranges_missing", [False, True]) -def test_deleted_ranges_allow_nonconflicting_changes(binding_with_deleted_range, all_ranges_missing): - db = binding_with_deleted_range +def test_deleted_ranges_allow_nonconflicting_changes(binding_with_surviving_pools, all_ranges_missing): + db = binding_with_surviving_pools if all_ranges_missing: db.delete("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3") match = "vendor-a" if all_ranges_missing else "vendor-b" @@ -182,8 +194,8 @@ def test_deleted_ranges_allow_nonconflicting_changes(binding_with_deleted_range, ("100.1.1.40", "100.1.1.41", "partially overlapping pools"), ("100.1.3.10", "100.1.3.11", "is not in any subnet"), ]) -def test_surviving_range_update_remains_guarded(binding_with_deleted_range, start, end, error): - db = binding_with_deleted_range +def test_surviving_range_update_remains_guarded(binding_with_surviving_pools, start, end, error): + db = binding_with_surviving_pools db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|other", {"matches@": "vendor-b", "ips@": "100.1.1.40"}) before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} @@ -196,8 +208,8 @@ def test_surviving_range_update_remains_guarded(binding_with_deleted_range, star @pytest.mark.parametrize("operation", ["add", "update"]) -def test_candidate_with_missing_range_remains_strict(binding_with_deleted_range, operation): - db = binding_with_deleted_range +def test_candidate_with_missing_range_remains_strict(binding_with_surviving_pools, operation): + db = binding_with_surviving_pools before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} args = ["Vlan100", "other", "--match=vendor-b", "--range=range1,range3"] if operation == "add" else [ "Vlan100", "surviving", "--match=vendor-b"] @@ -209,6 +221,78 @@ def test_candidate_with_missing_range_remains_strict(binding_with_deleted_range, assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before +@pytest.mark.parametrize("binding_with_surviving_pools", ["shrunk-ips", "shrunk-ranges"], indirect=True) +@pytest.mark.parametrize("all_pools_off_subnet", [False, True]) +def test_prefix_shrink_allows_nonconflicting_changes(binding_with_surviving_pools, all_pools_off_subnet): + db = binding_with_surviving_pools + if all_pools_off_subnet: + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|surviving", + {"matches@": "vendor-a", "ips@": "100.1.1.200"}) + match = "vendor-a" if all_pools_off_subnet else "vendor-b" + + result = invoke(db, BINDING_COMMAND.commands["add"], ["Vlan100", "other", "--match=" + match, "100.1.1.40"]) + + assert result.exit_code == 0, result.output + + +@pytest.mark.parametrize("binding_with_surviving_pools", ["shrunk-ips", "shrunk-ranges"], indirect=True) +@pytest.mark.parametrize("operation", ["add", "update"]) +def test_candidate_after_prefix_shrink_remains_strict(binding_with_surviving_pools, operation): + db = binding_with_surviving_pools + existing = db.get_all("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|surviving") + args = ["Vlan100", "surviving", "--match=vendor-b"] + if operation == "add": + args[1] = "other" + args += [existing["ips@"]] if "ips@" in existing else ["--range=" + existing["ranges@"]] + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + + result = invoke(db, BINDING_COMMAND.commands[operation], args) + + assert result.exit_code == 2, result.output + assert "is not in any subnet" in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + + +@pytest.mark.parametrize("binding_with_surviving_pools", ["shrunk-ranges"], indirect=True) +@pytest.mark.parametrize("start,end,error", [ + ("100.1.1.40", "100.1.1.41", "partially overlapping pools"), + ("100.1.1.130", "100.1.1.140", "is not in any subnet"), +]) +def test_range_update_after_prefix_shrink_remains_guarded(binding_with_surviving_pools, start, end, error): + db = binding_with_surviving_pools + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|other", + {"matches@": "vendor-b", "ips@": "100.1.1.40"}) + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + + result = invoke(db, RANGE_COMMAND.commands["update"], ["range3", start, end]) + + assert result.exit_code == 2, result.output + assert error in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + + +@pytest.mark.parametrize("binding_with_surviving_pools", ["shrunk-ranges"], indirect=True) +def test_prefix_shrink_allows_repairing_range(binding_with_surviving_pools): + db = binding_with_surviving_pools + + result = invoke(db, RANGE_COMMAND.commands["update"], ["range1", "100.1.1.50", "100.1.1.60"]) + + assert result.exit_code == 0, result.output + assert db.get("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range1", "range@") == "100.1.1.50,100.1.1.60" + + +@pytest.mark.parametrize("binding_with_surviving_pools", ["shrunk-ips", "shrunk-ranges"], indirect=True) +def test_match_update_after_prefix_shrink_remains_guarded(binding_with_surviving_pools): + db = binding_with_surviving_pools + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + + result = invoke(db, MATCH_COMMAND.commands["update"], ["vendor-a", "--type=circuit_id", "--value=etp5"]) + + assert result.exit_code == 2, result.output + assert "is not a member of vlan Vlan100" in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + + @pytest.fixture def dhcp_vlan200(mock_db): mock_db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan200", diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 7742e6e7d55..0806cc46807 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -108,18 +108,18 @@ def add_pool_interval(intervals, subnets, start, end): return subnet is not None -def validate_ip_pool(ips, subnets, dhcp_interface): +def validate_ip_pool(ips, subnets, dhcp_interface, allow_off_subnet=False): intervals = {} for ip in ips: if not validate_str_type("ipv4-address", ip): click.get_current_context().fail("Illegal IP address {}".format(ip)) - if not add_pool_interval(intervals, subnets, ip, ip): + if not add_pool_interval(intervals, subnets, ip, ip) and not allow_off_subnet: click.get_current_context().fail("IP {} is not in any subnet of vlan {}".format(ip, dhcp_interface)) return intervals def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides=None, - allow_missing_ranges=False): + allow_missing_ranges=False, allow_off_subnet=False): intervals = {} for range_name in ranges: key = "DHCP_SERVER_IPV4_RANGE|" + range_name @@ -140,7 +140,8 @@ def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides click.get_current_context().fail("Range {} has an invalid IPv4 address".format(range_name)) if count_ipv4(ip_start, ip_end) < 1: click.get_current_context().fail("Range {} has an invalid address order".format(range_name)) - if not add_pool_interval(intervals, subnets, ip_start, ip_end): + if not add_pool_interval(intervals, subnets, ip_start, ip_end) and ( + not allow_off_subnet or (range_overrides and range_name in range_overrides)): click.get_current_context().fail( "Range {} is not in any subnet of vlan {}".format(range_name, dhcp_interface)) return intervals @@ -189,7 +190,8 @@ def resolve_port_alias(dbconn, alias, port_alias_map=None): def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_overrides=None, - range_overrides=None, port_alias_map=None, allow_missing_ranges=False): + range_overrides=None, port_alias_map=None, allow_missing_ranges=False, + allow_off_subnet=False): validate_key_name(binding_name, "Binding name", "|") if not dbconn.exists("CONFIG_DB", "DHCP_SERVER_IPV4|" + dhcp_interface): click.get_current_context().fail("Interface {} is not a valid dhcp interface".format(dhcp_interface)) @@ -222,10 +224,11 @@ def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_ov subnets = get_vlan_subnets(dbconn, dhcp_interface) if has_ips: - intervals = validate_ip_pool(split_csv(entry["ips@"], "IP list"), subnets, dhcp_interface) + intervals = validate_ip_pool(split_csv(entry["ips@"], "IP list"), subnets, dhcp_interface, + allow_off_subnet=allow_off_subnet) else: intervals = validate_range_pool(dbconn, split_csv(entry["ranges@"], "Range list"), subnets, - dhcp_interface, range_overrides, allow_missing_ranges) + dhcp_interface, range_overrides, allow_missing_ranges, allow_off_subnet) return conditions, {subnet: merge_pool_intervals(pool) for subnet, pool in intervals.items()} @@ -279,17 +282,18 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid predicates = {} pools = {} for binding_name in sorted(bindings): + is_candidate = candidate and binding_name == candidate[0] try: conditions, intervals = validate_binding_entry( dbconn, dhcp_interface, binding_name, bindings[binding_name], match_overrides, range_overrides, port_alias_map, - allow_missing_ranges=not (candidate and binding_name == candidate[0]) + allow_missing_ranges=not is_candidate, allow_off_subnet=not is_candidate ) - # Existing bindings still serve their surviving ranges, as dhcp_cfggen does. + # Existing bindings still serve their usable pools, as dhcp_cfggen does. if intervals: predicates[binding_name], pools[binding_name] = conditions, intervals except click.UsageError: - if candidate and binding_name == candidate[0]: + if is_candidate: raise # dhcp_cfggen skips a binding that is already invalid (for example after # its port left the VLAN), so it must not block unrelated changes. Only @@ -297,7 +301,8 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid if match_overrides or range_overrides: try: validate_binding_entry(dbconn, dhcp_interface, binding_name, bindings[binding_name], - port_alias_map=port_alias_map, allow_missing_ranges=True) + port_alias_map=port_alias_map, allow_missing_ranges=True, + allow_off_subnet=True) except click.UsageError: continue raise From c0867a85f003076b0063f3f04e6b723df3c57c19 Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Mon, 23 Nov 2026 00:41:55 +0000 Subject: [PATCH 5/9] Addressing comment by Copilot AI about ambiguous subnet membership Reject a MATCH pool that fits more than one distinct VLAN prefix in the CLI before writing Config DB, matching dhcp_cfggen. Treat several addresses on the same prefix as one subnet in both paths. Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 44 +++++++++++++++++++ .../cli/config/plugins/dhcp_server.py | 27 ++++++++---- .../dhcp_utilities/dhcpservd/dhcp_cfggen.py | 3 +- .../tests/test_dhcp_match_cfggen.py | 26 +++++++++++ 4 files changed, 91 insertions(+), 9 deletions(-) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index 7f13a4c8ea6..e4744cb9adc 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -1291,3 +1291,47 @@ def test_stale_binding_cannot_be_rewritten_invalid(self, mock_db): assert result.exit_code == 2 assert "is not a member of vlan Vlan100" in result.output + + +@pytest.fixture +def overlapping_prefix_db(prefix_db): + prefix_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") + prefix_db.hmset("CONFIG_DB", "VLAN_INTERFACE|Vlan100|100.1.1.129/25", {}) + prefix_db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|ambiguous", {"range@": "100.1.1.130,100.1.1.140"}) + return prefix_db + + +@pytest.mark.parametrize("operation", ["add-ip", "add-range", "existing-binding", "range-update"]) +def test_pool_in_overlapping_prefixes_rejected(overlapping_prefix_db, operation): + db = overlapping_prefix_db + if operation == "add-ip": + command, args = BINDING_COMMAND.commands["add"], ["Vlan100", "new", "100.1.1.130", "--match=port-etp2,vendor-a"] + elif operation == "add-range": + command, args = BINDING_COMMAND.commands["add"], ["Vlan100", "new", "--range=ambiguous", "--match=vendor-a"] + elif operation == "existing-binding": + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|old", {"matches@": "vendor-b", "ips@": "100.1.1.130"}) + command, args = BINDING_COMMAND.commands["add"], ["Vlan100", "new", "100.1.1.30", "--match=vendor-a"] + else: + db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|old", {"matches@": "vendor-b", "ranges@": "range3"}) + command, args = RANGE_COMMAND.commands["update"], ["range3", "100.1.1.130", "100.1.1.140"] + before = {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} + + result = invoke(db, command, args) + + assert result.exit_code == 2, result.output + assert "matches multiple IPv4 subnets of Vlan100" in result.output + assert {key: dict(db.get_all("CONFIG_DB", key)) for key in db.keys("CONFIG_DB", "*")} == before + + +@pytest.mark.parametrize("vlan_ip,pool_ip", [ + ("100.1.1.129/25", "100.1.1.30"), + ("100.1.1.2/24", "100.1.1.130"), +]) +def test_pool_in_single_prefix_accepted(prefix_db, vlan_ip, pool_ip): + prefix_db.set("CONFIG_DB", "DHCP_SERVER_IPV4|Vlan100", "mode", "MATCH") + prefix_db.hmset("CONFIG_DB", "VLAN_INTERFACE|Vlan100|" + vlan_ip, {}) + + result = invoke(prefix_db, BINDING_COMMAND.commands["add"], ["Vlan100", "new", pool_ip, "--match=vendor-a"]) + + assert result.exit_code == 0, result.output + assert prefix_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|new", "ips@") == pool_ip diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 0806cc46807..94486a3d947 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -98,14 +98,22 @@ def get_vlan_subnets(dbconn, dhcp_interface): return subnets -def add_pool_interval(intervals, subnets, start, end): - """Record an address interval under the first VLAN subnet that contains it.""" +class AmbiguousPoolError(click.UsageError): + """A pool fits more than one VLAN prefix, which dhcp_cfggen rejects for the whole configuration.""" + + +def add_pool_interval(intervals, subnets, start, end, dhcp_interface): + """Record an address interval under the single VLAN prefix that contains it.""" start = ipaddress.ip_address(start) end = ipaddress.ip_address(end) - subnet = next((subnet for subnet in subnets if start in subnet and end in subnet), None) - if subnet is not None: - intervals.setdefault(subnet, []).append((int(start), int(end))) - return subnet is not None + matching = sorted({subnet for subnet in subnets if start in subnet and end in subnet}, key=str) + if len(matching) > 1: + raise AmbiguousPoolError( + "Pool {}-{} matches multiple IPv4 subnets of {}".format(start, end, dhcp_interface), + ctx=click.get_current_context()) + if matching: + intervals.setdefault(matching[0], []).append((int(start), int(end))) + return bool(matching) def validate_ip_pool(ips, subnets, dhcp_interface, allow_off_subnet=False): @@ -113,7 +121,7 @@ def validate_ip_pool(ips, subnets, dhcp_interface, allow_off_subnet=False): for ip in ips: if not validate_str_type("ipv4-address", ip): click.get_current_context().fail("Illegal IP address {}".format(ip)) - if not add_pool_interval(intervals, subnets, ip, ip) and not allow_off_subnet: + if not add_pool_interval(intervals, subnets, ip, ip, dhcp_interface) and not allow_off_subnet: click.get_current_context().fail("IP {} is not in any subnet of vlan {}".format(ip, dhcp_interface)) return intervals @@ -140,7 +148,7 @@ def validate_range_pool(dbconn, ranges, subnets, dhcp_interface, range_overrides click.get_current_context().fail("Range {} has an invalid IPv4 address".format(range_name)) if count_ipv4(ip_start, ip_end) < 1: click.get_current_context().fail("Range {} has an invalid address order".format(range_name)) - if not add_pool_interval(intervals, subnets, ip_start, ip_end) and ( + if not add_pool_interval(intervals, subnets, ip_start, ip_end, dhcp_interface) and ( not allow_off_subnet or (range_overrides and range_name in range_overrides)): click.get_current_context().fail( "Range {} is not in any subnet of vlan {}".format(range_name, dhcp_interface)) @@ -292,6 +300,9 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid # Existing bindings still serve their usable pools, as dhcp_cfggen does. if intervals: predicates[binding_name], pools[binding_name] = conditions, intervals + except AmbiguousPoolError: + # dhcp_cfggen fails the whole generation here, not just this binding. + raise except click.UsageError: if is_candidate: raise diff --git a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py index ae789cdaf07..cbe22a07ede 100755 --- a/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py +++ b/src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py @@ -646,7 +646,8 @@ def _find_match_subnet(self, dhcp_interface_name, dhcp_interfaces, start, end): syslog.syslog(syslog.LOG_WARNING, "Pool {}-{} of {} is not in an IPv4 subnet, skip".format( start, end, dhcp_interface_name)) return None - if len(matching_subnets) > 1: + # Several addresses on one prefix are a single subnet; only distinct overlapping prefixes are ambiguous. + if len({interface["network"] for interface in matching_subnets}) > 1: raise ValueError( "Pool {}-{} matches multiple IPv4 subnets of {}".format(start, end, dhcp_interface_name) ) diff --git a/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py index b4bfa67ab1d..be9b70070c9 100644 --- a/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py +++ b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py @@ -628,3 +628,29 @@ def test_portchannel_added_after_start_is_resolved(): parsed = json.loads(config)["Dhcp4"] assert parsed["subnet4"][0]["pools"][0]["pool"] == "192.168.0.50 - 192.168.0.50" assert "sonic-host:PortChannel5".encode("utf-8").hex() in parsed["client-classes"][0]["test"] + + +def test_pool_in_overlapping_prefixes_is_rejected(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + interfaces = {"Vlan1000": [ + {"network": ipaddress.ip_network("192.168.0.0/24"), "ip": "192.168.0.1/24"}, + {"network": ipaddress.ip_network("192.168.0.128/25"), "ip": "192.168.0.129/25"} + ]} + bindings = {"Vlan1000|vendor-a": {"matches": ["port-etp7", "vendor-a"], "ips": ["192.168.0.130"]}} + + with pytest.raises(ValueError, match="matches multiple IPv4 subnets of Vlan1000"): + parse_bindings(generator, bindings, interfaces=interfaces) + + +def test_addresses_on_one_prefix_are_one_subnet(mock_swsscommon_dbconnector_init, mock_get_render_template): + generator = create_generator(mock_swsscommon_dbconnector_init, mock_get_render_template) + interfaces = {"Vlan1000": [ + {"network": ipaddress.ip_network("192.168.0.0/24"), "ip": "192.168.0.1/24"}, + {"network": ipaddress.ip_network("192.168.0.0/24"), "ip": "192.168.0.2/24"} + ]} + bindings = {"Vlan1000|vendor-a": {"matches": ["vendor-a"], "ips": ["192.168.0.130"]}} + + pools, _, _, _ = parse_bindings(generator, bindings, interfaces=interfaces) + + assert list(pools["Vlan1000"]) == ["192.168.0.1/24"] + assert pools["Vlan1000"]["192.168.0.1/24"][0]["range"] == "192.168.0.130 - 192.168.0.130" From 0b7d65fe55600f77bc9d8fcb76ef0f597d5f6948 Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Mon, 23 Nov 2026 00:58:28 +0000 Subject: [PATCH 6/9] Addressing review comment by Copilot AI about atomic binding replacement Replace a binding with DEL and HSET in one Redis MULTI/EXEC so dhcpservd never generates a configuration in which the binding is missing and a less specific class loses its exclusion. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Nishant Sharma --- .../cli-plugin-tests/conftest.py | 31 ++++++++++++++++++- .../test_config_dhcp_server_match.py | 6 ++++ .../cli/config/plugins/dhcp_server.py | 24 ++++++++++++-- 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/conftest.py b/dockers/docker-dhcp-server/cli-plugin-tests/conftest.py index b078aa77095..4d2a3b2ae82 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/conftest.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/conftest.py @@ -6,6 +6,7 @@ import sys import mock_tables +from swsscommon import swsscommon TEST_DATA_PATH = os.path.dirname(os.path.abspath(__file__)) @@ -102,4 +103,32 @@ def get_redis_client(table): redis_client_config_db.hdel = mock.Mock(side_effect=config_db_hdel) redis_client_state_db.hdel = mock.Mock(side_effect=state_db_hdel) - yield db + class RedisCommand: + def format(self, command): + self.command = list(command) + + class RedisTransactioner: + def __init__(self, client): + assert client is redis_client_config_db + self.commands = None + + def multi(self): + self.commands = [] + + def enqueue(self, command, expected_type): + self.commands.append(command.command) + + def _exec(self): + for name, key, *args in self.commands: + if name == "DEL": + mock_config_db.pop(key, None) + else: + assert name == "HSET" + mock_config_db.setdefault(key, {}).update(zip(args[::2], args[1::2])) + db.transactions.append(self.commands) + return True + + db.transactions = [] + with mock.patch.object(swsscommon, "RedisCommand", RedisCommand), \ + mock.patch.object(swsscommon, "RedisTransactioner", RedisTransactioner): + yield db diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index e4744cb9adc..045497e4d1c 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -1133,6 +1133,12 @@ def test_binding_update_switch_ips_to_range(self, mock_db): key = "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-a" assert mock_db.get("CONFIG_DB", key, "ranges@") == "range1" assert not mock_db.get("CONFIG_DB", key, "ips@") + # Replaced in one transaction so dhcpservd never sees the binding missing + assert mock_db.transactions == [[ + ["DEL", key], ["HSET", key, "matches@", "port-etp2,vendor-a", "ranges@", "range1"] + ]] + mock_db.delete.assert_not_called() + mock_db.hmset.assert_not_called() def test_binding_update_switch_range_to_ips(self, mock_db): result = invoke( diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 94486a3d947..c35fc2b62c2 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -5,6 +5,8 @@ import string import unicodedata +from swsscommon import swsscommon + SUPPORTED_TYPE = ["binary", "boolean", "ipv4-address", "string", "uint8", "uint16", "uint32"] SUPPORTED_MODE = ["PORT", "MATCH"] @@ -98,6 +100,23 @@ def get_vlan_subnets(dbconn, dhcp_interface): return subnets +REDIS_REPLY_INTEGER = 3 + + +def replace_config_db_entry(dbconn, key, entry): + """Replace a Config DB hash in one MULTI/EXEC so subscribers never read it missing or half-written.""" + transaction = swsscommon.RedisTransactioner(dbconn.get_redis_client("CONFIG_DB")) + transaction.multi() + fields = [item for field in sorted(entry) for item in (field, entry[field])] + for command in (["DEL", key], ["HSET", key] + fields): + redis_command = swsscommon.RedisCommand() + redis_command.format(command) + transaction.enqueue(redis_command, REDIS_REPLY_INTEGER) + # SWIG exposes RedisTransactioner::exec() as _exec() + if not transaction._exec(): + click.get_current_context().fail("Failed to update {}".format(key)) + + class AmbiguousPoolError(click.UsageError): """A pool fits more than one VLAN prefix, which dhcp_cfggen rejects for the whole configuration.""" @@ -765,8 +784,9 @@ def dhcp_server_ipv4_binding_update(db, dhcp_interface, binding_name, match_list entry["ranges@"] = existing.get("ranges@", "") validate_vlan_bindings(dbconn, dhcp_interface, candidate=(binding_name, entry)) - dbconn.delete("CONFIG_DB", key) - dbconn.hmset("CONFIG_DB", key, entry) + # A separate delete would let dhcpservd briefly generate without this binding, + # dropping its exclusion from less specific classes. + replace_config_db_entry(dbconn, key, entry) @dhcp_server_ipv4_binding.command(name="del") From 412a5dcab051cef922492e982977483bf2ff2380 Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Tue, 24 Nov 2026 01:54:47 +0000 Subject: [PATCH 7/9] Addressing review comment about range recreate validation A forced range delete leaves bindings referencing the range name, so re-adding that name could reintroduce a pool configuration the generator rejects (partial overlap or off-subnet). Validate range add against existing references like range update, before any Config DB write. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 21 +++++++++++++++++++ .../cli/config/plugins/dhcp_server.py | 2 ++ 2 files changed, 23 insertions(+) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index 045497e4d1c..1a338359d85 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -1246,6 +1246,27 @@ def test_range_update_causing_partial_pool_overlap_rejected(self, mock_db): assert "Bindings fallback and maia-a have partially overlapping pools on Vlan100" in result.output assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3", "range@") == "100.1.1.10" + @pytest.mark.parametrize("start,end,error", [ + ("100.1.1.10", "100.1.1.20", "Bindings fallback and maia-a have partially overlapping pools on Vlan100"), + ("100.1.2.10", "100.1.2.10", "Range range3 is not in any subnet of vlan Vlan100"), + ("100.1.1.10", "100.1.1.10", None), + ]) + def test_range_recreate_after_force_delete_is_validated(self, mock_db, start, end, error): + """fallback still references range3 after a forced delete, so re-adding it must pass binding validation.""" + result = invoke(mock_db, RANGE_COMMAND.commands["del"], ["range3", "--force"]) + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|fallback", "ranges@") == "range3" + + result = invoke(mock_db, RANGE_COMMAND.commands["add"], ["range3", start, end]) + + if error: + assert result.exit_code == 2, result.output + assert error in result.output + assert not mock_db.exists("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3") + else: + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3", "range@") == start + "," + end + def test_enable_match_interface_with_partial_pool_overlap_rejected(self, mock_db): mock_db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-b", {"matches@": "port-etp2,vendor-b", "ips@": "100.1.1.20,100.1.1.21"}) diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index c35fc2b62c2..274b6a9d7a8 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -581,6 +581,8 @@ def dhcp_server_ipv4_range_add(db, range_name, ip_start, ip_end): if dbconn.exists("CONFIG_DB", key): ctx.fail("Range {} already exist".format(range_name)) else: + # Bindings can still reference a force-deleted range, so recreating it is validated like an update. + validate_range_update(dbconn, range_name, ip_start + "," + ip_end) dbconn.hmset("CONFIG_DB", key, {"range@": ip_start + "," + ip_end}) From 8a4c19277c6664c26aba903e7a3125e6a85d2124 Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Fri, 27 Nov 2026 05:08:48 +0000 Subject: [PATCH 8/9] Addressing review comment about stale bindings becoming generation-fatal dhcp_cfggen skips a binding whose match is missing or whose circuit ID port left the VLAN, but fails the whole generation for other binding errors such as two matches of the same type. The CLI accepted any update to an already-invalid binding, so retyping a match on a stale binding could persist a configuration that stops dhcpservd from starting. Raise StaleBindingError for the conditions dhcp_cfggen skips, and reject an update that turns a skipped binding into a generation failure. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 24 +++++++++++++++++++ .../cli/config/plugins/dhcp_server.py | 22 ++++++++++++----- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index 1a338359d85..549e79d4123 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -1319,6 +1319,30 @@ def test_stale_binding_cannot_be_rewritten_invalid(self, mock_db): assert result.exit_code == 2 assert "is not a member of vlan Vlan100" in result.output + @pytest.mark.parametrize("matches", ["port-etp2,vendor-a", "vendor-a,port-etp2"]) + def test_stale_binding_cannot_become_generation_fatal(self, mock_db, matches): + # maia-a is skipped by dhcp_cfggen while Ethernet2 is outside the VLAN, but + # retyping port-etp2 to option60 gives it two option60 matches, which + # dhcp_cfggen rejects for the whole configuration instead of skipping. + mock_db.delete("CONFIG_DB", "VLAN_MEMBER|Vlan100|Ethernet2") + mock_db.set("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-a", "matches@", matches) + + result = invoke(mock_db, MATCH_COMMAND.commands["update"], ["port-etp2", "--type=option60", "--value=NEW"]) + + assert result.exit_code == 2 + assert "cannot reference multiple matches of type option60" in result.output + assert mock_db.get_all("CONFIG_DB", "DHCP_SERVER_IPV4_MATCH|port-etp2") == { + "type": "circuit_id", "value": "etp2" + } + + def test_stale_binding_can_stay_stale(self, mock_db): + mock_db.delete("CONFIG_DB", "VLAN_MEMBER|Vlan100|Ethernet2") + + result = invoke(mock_db, MATCH_COMMAND.commands["update"], ["port-etp2", "--value=etp5"]) + + assert result.exit_code == 0, result.output + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_MATCH|port-etp2", "value") == "etp5" + @pytest.fixture def overlapping_prefix_db(prefix_db): diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 274b6a9d7a8..7fd764c302a 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -121,6 +121,10 @@ class AmbiguousPoolError(click.UsageError): """A pool fits more than one VLAN prefix, which dhcp_cfggen rejects for the whole configuration.""" +class StaleBindingError(click.UsageError): + """A binding references a missing match or a port outside its VLAN, which dhcp_cfggen skips.""" + + def add_pool_interval(intervals, subnets, start, end, dhcp_interface): """Record an address interval under the single VLAN prefix that contains it.""" start = ipaddress.ip_address(start) @@ -180,7 +184,7 @@ def get_match_entry(dbconn, match_name, match_overrides=None): else: key = "DHCP_SERVER_IPV4_MATCH|" + match_name if not dbconn.exists("CONFIG_DB", key): - click.get_current_context().fail("Match {} does not exist".format(match_name)) + raise StaleBindingError("Match {} does not exist".format(match_name), ctx=click.get_current_context()) entry = dbconn.get_all("CONFIG_DB", key) if entry.get("type") not in SUPPORTED_MATCH_TYPE: click.get_current_context().fail("Match {} has unsupported type {}".format(match_name, entry.get("type", ""))) @@ -210,7 +214,7 @@ def resolve_port_alias(dbconn, alias, port_alias_map=None): port_alias_map.setdefault(portchannel, []).append(portchannel) ports = port_alias_map.get(alias, []) if not ports: - click.get_current_context().fail("Circuit ID alias {} does not exist".format(alias)) + raise StaleBindingError("Circuit ID alias {} does not exist".format(alias), ctx=click.get_current_context()) if len(ports) > 1: click.get_current_context().fail("Circuit ID alias {} is ambiguous".format(alias)) return ports[0] @@ -240,9 +244,9 @@ def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_ov if match_type == "circuit_id": port = resolve_port_alias(dbconn, match["value"], port_alias_map) if not dbconn.exists("CONFIG_DB", "VLAN_MEMBER|{}|{}".format(dhcp_interface, port)): - click.get_current_context().fail( - "Circuit ID alias {} is not a member of vlan {}".format(match["value"], dhcp_interface) - ) + raise StaleBindingError( + "Circuit ID alias {} is not a member of vlan {}".format(match["value"], dhcp_interface), + ctx=click.get_current_context()) has_ips = bool(entry.get("ips@")) has_ranges = bool(entry.get("ranges@")) @@ -322,7 +326,7 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid except AmbiguousPoolError: # dhcp_cfggen fails the whole generation here, not just this binding. raise - except click.UsageError: + except click.UsageError as error: if is_candidate: raise # dhcp_cfggen skips a binding that is already invalid (for example after @@ -333,6 +337,12 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid validate_binding_entry(dbconn, dhcp_interface, binding_name, bindings[binding_name], port_alias_map=port_alias_map, allow_missing_ranges=True, allow_off_subnet=True) + except StaleBindingError: + # A skipped binding must stay skippable: errors other than a stale + # match or port make dhcp_cfggen fail the whole generation. + if isinstance(error, StaleBindingError): + continue + raise error except click.UsageError: continue raise From 495eef0d0163981657d0b5bb6c7f616651626957 Mon Sep 17 00:00:00 2001 From: Nishant Sharma Date: Fri, 27 Nov 2026 05:45:49 +0000 Subject: [PATCH 9/9] Keep pools of skipped MATCH bindings reserved dhcp_cfggen skips a binding while its circuit ID port is outside the VLAN and restores it when the port is re-added. The CLI ignored such bindings entirely, so a new binding or range update could partially overlap a skipped binding's pool; re-adding the port then failed generation and stopped dhcpservd from starting. Keep the pools of skipped bindings in the CLI pool overlap and prefix checks, while still excluding them from the predicate checks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Nishant Sharma --- .../test_config_dhcp_server_match.py | 20 ++++++++++++ .../cli/config/plugins/dhcp_server.py | 32 ++++++++++++++----- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py index 549e79d4123..2958f87c355 100644 --- a/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py +++ b/dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py @@ -1343,6 +1343,26 @@ def test_stale_binding_can_stay_stale(self, mock_db): assert result.exit_code == 0, result.output assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_MATCH|port-etp2", "value") == "etp5" + @pytest.mark.parametrize("operation", ["binding-add", "range-update"]) + def test_stale_binding_pool_stays_reserved(self, mock_db, operation): + # fallback (range3 = 100.1.1.10) is skipped while Ethernet2 is outside the VLAN, but + # re-adding the port restores it, so a partial overlap would then fail generation. + mock_db.delete("CONFIG_DB", "VLAN_MEMBER|Vlan100|Ethernet2") + mock_db.hmset("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|maia-a", + {"matches@": "vendor-a", "ips@": "100.1.1.20"}) + if operation == "binding-add": + command, args = BINDING_COMMAND.commands["add"], ["Vlan100", "new", "--match=vendor-b", + "100.1.1.10,100.1.1.11"] + else: + command, args = RANGE_COMMAND.commands["update"], ["range3", "100.1.1.20", "100.1.1.21"] + + result = invoke(mock_db, command, args) + + assert result.exit_code == 2 + assert "partially overlapping pools" in result.output + assert not mock_db.exists("CONFIG_DB", "DHCP_SERVER_IPV4_BINDING|Vlan100|new") + assert mock_db.get("CONFIG_DB", "DHCP_SERVER_IPV4_RANGE|range3", "range@") == "100.1.1.10" + @pytest.fixture def overlapping_prefix_db(prefix_db): diff --git a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py index 7fd764c302a..2af0bf9f466 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -248,6 +248,12 @@ def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_ov "Circuit ID alias {} is not a member of vlan {}".format(match["value"], dhcp_interface), ctx=click.get_current_context()) + return conditions, get_binding_pools(dbconn, dhcp_interface, entry, range_overrides, + allow_missing_ranges, allow_off_subnet) + + +def get_binding_pools(dbconn, dhcp_interface, entry, range_overrides=None, allow_missing_ranges=False, + allow_off_subnet=False): has_ips = bool(entry.get("ips@")) has_ranges = bool(entry.get("ranges@")) if has_ips == has_ranges: @@ -260,7 +266,7 @@ def validate_binding_entry(dbconn, dhcp_interface, binding_name, entry, match_ov else: intervals = validate_range_pool(dbconn, split_csv(entry["ranges@"], "Range list"), subnets, dhcp_interface, range_overrides, allow_missing_ranges, allow_off_subnet) - return conditions, {subnet: merge_pool_intervals(pool) for subnet, pool in intervals.items()} + return {subnet: merge_pool_intervals(pool) for subnet, pool in intervals.items()} def merge_pool_intervals(intervals): @@ -340,20 +346,30 @@ def validate_vlan_bindings(dbconn, dhcp_interface, candidate=None, match_overrid except StaleBindingError: # A skipped binding must stay skippable: errors other than a stale # match or port make dhcp_cfggen fail the whole generation. - if isinstance(error, StaleBindingError): - continue + if not isinstance(error, StaleBindingError): + raise error + except click.UsageError: + continue + else: raise error + if isinstance(error, StaleBindingError): + # The binding returns once its match or port does, so keep its pools + # reserved against the other bindings. + try: + stale_pools = get_binding_pools(dbconn, dhcp_interface, bindings[binding_name], range_overrides, + allow_missing_ranges=True, allow_off_subnet=True) except click.UsageError: continue - raise + if stale_pools: + pools[binding_name] = stale_pools validate_single_prefix(dhcp_interface, (subnet for pool in pools.values() for subnet in pool)) - binding_names = sorted(predicates) + binding_names = sorted(pools) for index, first_name in enumerate(binding_names): for second_name in binding_names[index + 1:]: - first = predicates[first_name] - second = predicates[second_name] - if len(first) == len(second) and predicates_overlap(first, second): + first = predicates.get(first_name) + second = predicates.get(second_name) + if first and second and len(first) == len(second) and predicates_overlap(first, second): click.get_current_context().fail( "Bindings {} and {} overlap with equal specificity on {}".format( first_name, second_name, dhcp_interface