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 d088931d645..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 @@ -15,12 +15,284 @@ 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 return CliRunner().invoke(command, args, obj=db) +@pytest.fixture +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"}) + 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_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} + 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_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" + + 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_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("operation", ["add", "update"]) +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"] + + 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.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", @@ -28,6 +300,60 @@ 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 == 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") + 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 == 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|*")): mock_db.delete("CONFIG_DB", key) @@ -282,8 +608,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, @@ -808,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( @@ -889,3 +1220,189 @@ 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" + + @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"}) + 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 + + @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.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): + 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 5f275986105..2af0bf9f466 100644 --- a/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py +++ b/dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py @@ -5,8 +5,11 @@ import string import unicodedata +from swsscommon import swsscommon + SUPPORTED_TYPE = ["binary", "boolean", "ipv4-address", "string", "uint8", "uint16", "uint32"] +SUPPORTED_MODE = ["PORT", "MATCH"] SUPPORTED_MATCH_TYPE = ["circuit_id", "option60"] @@ -97,21 +100,66 @@ def get_vlan_subnets(dbconn, dhcp_interface): return subnets -def validate_ip_pool(ips, subnets, dhcp_interface): +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.""" + + +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) + end = ipaddress.ip_address(end) + 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): + 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, 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 -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, allow_off_subnet=False): + intervals = {} for range_name in ranges: key = "DHCP_SERVER_IPV4_RANGE|" + range_name if range_overrides and range_name in 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 [] @@ -123,10 +171,11 @@ 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, 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)) + return intervals def get_match_entry(dbconn, match_name, match_overrides=None): @@ -135,12 +184,12 @@ 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", ""))) - 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 @@ -165,14 +214,15 @@ 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] 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, + 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)) @@ -194,10 +244,16 @@ 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()) + + 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: @@ -205,17 +261,50 @@ 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, + allow_off_subnet=allow_off_subnet) 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, allow_missing_ranges, allow_off_subnet) + return {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): bindings = {} @@ -226,38 +315,83 @@ 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 = {} + 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 - ) - - binding_names = sorted(predicates) + 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 is_candidate, allow_off_subnet=not is_candidate + ) + # 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 as error: + 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 + # 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, 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 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 + 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(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 ) ) + 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|*"): @@ -306,7 +440,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 @@ -320,8 +454,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 +519,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) updates["mode"] = mode if lease_time: if not validate_str_type("uint32", lease_time): @@ -422,6 +558,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) dbconn.set("CONFIG_DB", key, "state", "enabled") else: ctx.fail("Failed to enable, dhcp interface {} does not exist".format(dhcp_interface)) @@ -469,6 +607,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}) @@ -672,8 +812,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") 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..cbe22a07ede 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): @@ -44,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) @@ -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,54 @@ 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: + 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: + 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 + 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: + 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 +371,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 +564,335 @@ 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 len(ports) > 1: + raise ValueError("Circuit ID value {} is ambiguous".format(value)) + # 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") + 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): + matching_subnets = [ + interface for interface in dhcp_interfaces.get(dhcp_interface_name, []) + if start in interface["network"] and end in interface["network"] + ] + if not matching_subnets: + syslog.syslog(syslog.LOG_WARNING, "Pool {}-{} of {} is not in an IPv4 subnet, skip".format( + start, end, dhcp_interface_name)) + return None + # 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) + ) + 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 + ) + 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: + 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 + ) + 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) + 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: + 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): + 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 + )) + + 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 + ) + 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: + skip_reason = "circuit ID value {} is not a member of {}".format( + condition["value"], dhcp_interface_name + ) + break + conditions[condition["type"]] = condition + if skip_reason: + syslog.syslog(syslog.LOG_WARNING, "Binding {}: {}, skip".format(binding_key, skip_reason)) + continue + + intervals_by_subnet, _ = self._parse_binding_pools( + dhcp_interface_name, + binding_name, + binding_config, + dhcp_interfaces, + 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": binding_key, + "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..67e71f0915f 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_path = candidate.name + candidate.write(kea_dhcp4_config) + candidate.flush() + os.fsync(candidate.fileno()) + + 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..be9b70070c9 --- /dev/null +++ b/src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py @@ -0,0 +1,656 @@ +import ipaddress +import json +import syslog +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, {}) + + +@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( + 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", [ + ({ + "Vlan1000|duplicate-type": { + "matches": ["vendor-a", "vendor-b"], + "ips": ["192.168.0.20"] + } + }, "multiple matches of type option60") +]) +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) + + +@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|stale": binding, + "Vlan1000|healthy": {"matches": ["vendor-b"], "ips": ["192.168.0.40"]} + } + + 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): + 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"} + + +@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) + + +@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"}}, + "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"]} + + 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"] + + +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" 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; } }