Repository navigation
[dhcp_server] match mode core logic in dhcp-server - #30361
nishant111 wants to merge 9 commits into
Conversation
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved validation and mapping issues can leave accepted changes unapplied, keep deleted pools serving, or prevent DHCP startup.
5 open issues
Reject partially overlapping pools before committing bindings · New Prevent deleting the final binding on enabled MATCH interfaces · New Ensure unique subnet IDs for multi-prefix MATCH configurations · New Validate option60 UTF-8 byte length before accepting bindings · New Resolve MATCH interfaces from current Config DB data · New
What changed in this PR
Adds match-based DHCPv4 address assignment across SONiC’s configuration model, CLI, and Kea configuration generator, alongside lease-clearing support.
Changes:
- Adds circuit-ID and vendor-class conditions, pool bindings, validation, and configuration/show commands.
- Generates specificity-based Kea client classes and validates candidate configurations before replacing the live file.
- Adds scoped lease clearing, recovery monitoring, documentation, and regression tests.
| File | Description |
|---|---|
src/sonic-yang-models/yang-models/sonic-dhcp-server-ipv4.yang |
Defines MATCH mode, conditions, bindings, and constraints. |
src/sonic-yang-models/tests/yang_model_tests/tests/dhcp_server_ipv4_match.json |
Defines schema validation cases. |
src/sonic-yang-models/tests/yang_model_tests/tests_config/dhcp_server_ipv4_match.json |
Supplies schema test configurations. |
src/sonic-yang-models/tests/yang_model_pytests/test_dhcp_server_ipv4_match.py |
Tests key whitespace and circuit-ID ambiguity. |
src/sonic-yang-models/doc/Configuration.md |
Documents match tables and binding precedence. |
src/sonic-yang-mgmt/tests/libyang-python-tests/test_sonic_yang.py |
Tests translation recovery and key preservation. |
src/sonic-yang-mgmt/sonic_yang_ext.py |
Preserves DHCP keys and resets traversal state after failures. |
src/sonic-dhcp-utilities/tests/test_smart_switch.py |
Updates smart-switch generation expectations. |
src/sonic-dhcp-utilities/tests/test_dhcpservd.py |
Tests candidate validation and recovery behavior. |
src/sonic-dhcp-utilities/tests/test_dhcp_match_cfggen.py |
Tests match compilation, precedence, and pool validation. |
src/sonic-dhcp-utilities/tests/test_dhcp_db_monitor.py |
Tests match/binding events and recovery monitoring. |
src/sonic-dhcp-utilities/tests/test_dhcp_cfggen.py |
Updates generator results and hook expectations. |
src/sonic-dhcp-utilities/tests/test_data/kea-dhcp4.conf.j2 |
Adds the lease-command hook to the test template. |
src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcpservd.py |
Validates candidate files and tracks recovery subscriptions. |
src/sonic-dhcp-utilities/dhcp_utilities/dhcpservd/dhcp_cfggen.py |
Compiles MATCH bindings into Kea pools and classes. |
src/sonic-dhcp-utilities/dhcp_utilities/common/dhcp_db_monitor.py |
Monitors match/binding changes and recovery events. |
dockers/docker-dhcp-server/kea-dhcp4.conf.j2 |
Enables Kea lease commands. |
dockers/docker-dhcp-server/cli/show/plugins/show_dhcp_server.py |
Displays match conditions and bindings. |
dockers/docker-dhcp-server/cli/config/plugins/dhcp_server.py |
Adds MATCH configuration commands and validation. |
dockers/docker-dhcp-server/cli/clear/plugins/clear_dhcp_server.py |
Clears scoped leases and waits for State DB synchronization. |
dockers/docker-dhcp-server/cli-plugin-tests/test_show_dhcp_server_match.py |
Tests filtered and literal-name display commands. |
dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server.py |
Adjusts interface deletion coverage for new fixtures. |
dockers/docker-dhcp-server/cli-plugin-tests/test_config_dhcp_server_match.py |
Tests match/binding commands and validation. |
dockers/docker-dhcp-server/cli-plugin-tests/test_clear_dhcp_server.py |
Tests lease-clearing scope, synchronization, and failures. |
dockers/docker-dhcp-server/cli-plugin-tests/mock_config_db.json |
Adds port aliases, conditions, and binding fixtures. |
Review effort: Balanced
f036cb3 to
3283ba3
Compare
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
742239d to
b4ed7d7
Compare
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
There was a problem hiding this comment.
🟡 Changes recommended
Critical alias synchronization and binding update/validation flaws can prevent DHCP leases, assign addresses from the wrong pool, or leave CLI-accepted changes unapplied.
4 open issues
5 resolved since last review
Ensure unique subnet IDs for multi-prefix MATCH configurations Prevent deleting the final binding on enabled MATCH interfaces Reject partially overlapping pools before committing bindings Resolve MATCH interfaces from current Config DB data Validate option60 UTF-8 byte length before accepting bindings
Review effort: Balanced
|
/azp run Azure.sonic-buildimage |
|
@nishant111 Thanks for the updates. Re-reviewed head One additional P2 remains before merge: recreating a referenced range bypasses cross-binding validation.
Reproduced with a MATCH-enabled
Please apply the same prospective-range/cross-binding validation before adding a range referenced by existing bindings, and add regression coverage for force-delete/recreate, including rejection without writing the invalid range. Please also update the test evidence to identify the exact tested head and include results/logs for the follow-up fixes and this regression. The description still names |
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
/azpw ms_conflict |
1 similar comment
|
/azpw ms_conflict |
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
A forced range delete leaves bindings referencing the range name, so re-adding that name could reintroduce a pool configuration the generator rejects (partial overlap or off-subnet). Validate range add against existing references like range update, before any Config DB write. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Nishant Sharma <nshntsharma86@gmail.com>
9031ac7 to
412a5dc
Compare
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
<!-- Please make sure you've read and understood our contributing guidelines; https://github.com/sonic-net/SONiC/blob/gh-pages/CONTRIBUTING.md Please provide following information to help code review process a bit easier: --> ### Description of PR <!-- - Please include a summary of the change and which issue is fixed. - Please also include relevant motivation and context. Where should reviewer start? background context? - List any dependencies that are required for this change. --> Summary: Add a test plan for IPv4 DHCP server MATCH mode, covering Circuit ID (Option 82) and Vendor Class Identifier (Option 60) matching. The plan defines 43 scenarios covering address assignment, AND/OR matching, specificity and exhaustion, runtime configuration changes, CLI validation, lease clearing, persistence, PORT/MATCH coexistence, and scale. This PR contains documentation only; automated tests will follow separately. Related design and implementation: - HLD: sonic-net/SONiC#2535 - YANG model: sonic-net/sonic-buildimage#29925 - CLI: sonic-net/sonic-buildimage#30159 - Core implementation: sonic-net/sonic-buildimage#30361 Executing the planned tests requires an image containing the applicable model, CLI and core implementation changes. Fixes # (issue): N/A — feature test-plan documentation. <!-- If you request a backport/cherry-pick below, link the GitHub issue or ADO work item here (for example, "Fixes #<issue>" or "ADO: <work item URL>"). --> ### Type of change Documentation only <!-- - Fill x for your type of change. - e.g. - [x] Bug fix --> - [ ] Bug fix - [ ] Testbed and Framework(new/improvement) - [ ] New Test case - [ ] Skipped for non-supported platforms - [ ] Test case improvement ### Back port request <!-- Only check a release or feature branch when the PR links a GitHub issue or ADO work item above. The linked tracker should explain the failure in detail, including whether it is a day-one issue or a regression, the affected branch/image/platform/test, and why this branch needs the fix. Backport or cherry-pick requests without a linked issue/work item may not be favored. If you request a backport/cherry-pick, provide both: 1. A GitHub issue or Microsoft ADO work item tracking the change. 2. Test evidence from the target branch(es) requested below. --> - [ ] 202311 - [ ] 202405 - [ ] 202411 - [ ] 202505 - [ ] 202511 - [ ] 202512 - [ ] 202605 Tracking issue/work item for backport/cherry-pick request (GitHub issue or Microsoft ADO): Failure type: <!-- day-one issue / regression / other --> ### Tested branch <!-- Select each branch where the change was tested. If you request a backport/cherry-pick, select the base branch and the tested target release branch(es). --> - [ ] master - [ ] 202311 - [ ] 202405 - [ ] 202411 - [ ] 202505 - [ ] 202511 - [ ] 202512 - [ ] 202605 - [ ] N/A ### Test result <!-- Provide the tested image version and test evidence for each selected branch. For example: - master: 20260716.01 - <test result or link> - 202605: 20260531.42 - <test result or link> --> ### Approach #### What is the motivation for this PR? Define end-to-end acceptance and regression coverage for DHCP server MATCH mode before implementing sonic-mgmt tests. The plan complements product unit tests by covering real relay behaviour, packaged Kea, SWSS/State DB synchronization, and lease deletion persistenc #### How did you do it? Reviewed the MATCH HLD, product model/CLI/core changes, and existing DHCP server tests. Organized the coverage into compact scenario tables with expected results, shared setup guidance, and topology requirements. #### How did you verify/test it? <!-- Summarize the overall validation here. For a backport/cherry-pick request, provide branch-specific image versions and evidence in the Test result section. --> na #### Any platform specific information? na #### Supported testbed topology if it's a new test case? na ### Documentation <!-- (If it's a new feature, new test case) Did you update documentation/Wiki relevant to your implementation? Link to the wiki page? --> na --------- Signed-off-by: Nishant Sharma <nshntsharma86@gmail.com>
Addressed this comment, CI is now passing, the one failed is optional and is failing for other PR's as well |
StormLiangMS
left a comment
There was a problem hiding this comment.
@nishant111 - Request changes: one reproduced validation mismatch can make a successful match update prevent all subsequent Kea configuration generation and daemon startup. See the inline finding at validate_vlan_bindings().
Reviewed head: 412a5dcab051cef922492e982977483bf2ff2380.
The description covers motivation, implementation, testing, and schema changes. DCO, EasyCLA, builds, and required test checks pass. The optional dualtor-vpp check failed in Prepare Testbed with 'NoneType' object has no attribute 'client'; zero tests ran in that job.
34 existing MATCH generator tests passed in an isolated Windows run with native SONiC adapters stubbed. The focused reproducer additionally confirmed successful CLI persistence, whole-generation failure, last-known-good config retention, and startup exit 1. The full native SONiC suite could not run here because swsscommon is unavailable.
dhcp_cfggen skips a binding whose match is missing or whose circuit ID port left the VLAN, but fails the whole generation for other binding errors such as two matches of the same type. The CLI accepted any update to an already-invalid binding, so retyping a match on a stale binding could persist a configuration that stops dhcpservd from starting. Raise StaleBindingError for the conditions dhcp_cfggen skips, and reject an update that turns a skipped binding into a generation failure. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Nishant Sharma <nshntsharma86@gmail.com>
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Copilot review overview
5 open issues
subprocess.run(...)is called but this diff doesn’t add an import forsubprocessin… · New Hard-coding the Redis reply type as3is brittle and obscures intent. If the Python bindings… · New Hard-coding the Redis reply type as3is brittle and obscures intent. If the Python bindings… · New UsingNamedTemporaryFilewill create the candidate with default permissions (typically0600),… · New UsingNamedTemporaryFilewill create the candidate with default permissions (typically0600),… · New
Review effort: Lite
| validation = subprocess.run( | ||
| [self.kea_dhcp4_binary, "-t", candidate_path], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=KEA_VALIDATION_TIMEOUT | ||
| ) |
| REDIS_REPLY_INTEGER = 3 | ||
|
|
||
|
|
| for command in (["DEL", key], ["HSET", key] + fields): | ||
| redis_command = swsscommon.RedisCommand() | ||
| redis_command.format(command) | ||
| transaction.enqueue(redis_command, REDIS_REPLY_INTEGER) |
| 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()) |
| self._enable_recovery_checkers() | ||
| return False | ||
|
|
||
| os.replace(candidate_path, self.kea_dhcp4_config_path) |
dhcp_cfggen skips a binding while its circuit ID port is outside the VLAN and restores it when the port is re-added. The CLI ignored such bindings entirely, so a new binding or range update could partially overlap a skipped binding's pool; re-adding the port then failed generation and stopped dhcpservd from starting. Keep the pools of skipped bindings in the CLI pool overlap and prefix checks, while still excluding them from the predicate checks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Signed-off-by: Nishant Sharma <nshntsharma86@gmail.com>
|
/azp run Azure.sonic-buildimage |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Copilot review overview
9 open issues
Fortype=circuit_id,dhcp_cfggenencodes the match as{hostname}:{value}before enforcing the… · New Fortype=circuit_id,dhcp_cfggenencodes the match as{hostname}:{value}before enforcing the… · Newsubprocess.run(...)is called but this diff doesn’t add an import forsubprocessin… Avoid hard-coding reply type3for RedisTransactioner.enqueue(). This is a brittle magic number… · New UsingNamedTemporaryFilewill create the candidate with default permissions (typically0600),… UsingNamedTemporaryFilewill create the candidate with default permissions (typically0600),… Hard-coding the Redis reply type as3is brittle and obscures intent. If the Python bindings… Hard-coding the Redis reply type as3is brittle and obscures intent. If the Python bindings… Correct typo in comment: 'Verfiy' → 'Verify'. · New
Review effort: Lite
| return intervals | ||
|
|
||
|
|
||
| def get_match_entry(dbconn, match_name, match_overrides=None): |
| 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)) |
|
|
||
|
|
||
| def validate_ip_pool(ips, subnets, dhcp_interface): | ||
| REDIS_REPLY_INTEGER = 3 |
| ) | ||
| dhcpservd.enabled_checker = enabled_checker | ||
| assert dhcpservd.dump_dhcp4_config() | ||
| # Verfiy whether generate() func of dhcp_cfggen is called |



Why I did it
This is Phase 3 of DHCP server MATCH mode, following the HLD. It makes the DHCP server actually use the MATCH configuration added by the earlier phases.
DHCP_SERVER_IPV4_MATCHandDHCP_SERVER_IPV4_BINDING.config dhcp_server ipv4 match|bindingCLI.dhcpservddid not read either table, andmodedid not acceptMATCH.This PR lets a VLAN run in
MATCHmode. Address pools are picked by composable match conditions: the client's port (Option 82 circuit-id) and/or its vendor class (Option 60). PORT mode keeps working as before.Test plan: sonic-net/sonic-mgmt#28933
Work item tracking
How I did it
YANG / docs
sonic-dhcp-server-ipv4.yang: themodeleaf now acceptsMATCH.Configuration.md.Config generation (
dhcp_cfggen.py)circuit_idis matched against the relay agent's Option 82 sub-option 1.option60is matched asoption[60].hex.ValueError:ipsandranges;dhcpservd / DB monitor
DhcpMatchTableEventCheckerwatches matches in use;DhcpBindingTableEventCheckerwatches bindings on enabled MATCH interfaces.dhcpservdwrites a candidate config, validates it withkea-dhcp4 -t, and only then activates it with an atomic rename.CLI (
dhcp_server.py)binding add/updatenow runs the same cross-binding validation the generator uses, so a bad config is rejected before it is written to Config DB. This includes:binding updatereplaces the entry withDEL+HSETin a single RedisMULTI/EXECviaswsscommon.RedisTransactioner. With separate writes,dhcpservdcould briefly generate a config without the binding.How to verify it
dockers/docker-dhcp-server/cli-plugin-tests: 399 passed.src/sonic-dhcp-utilities/tests: 437 passed. This includes the newtest_dhcp_match_cfggen.py.Which release branch to backport (provide reason below if selected)
Tracking issue/work item for backport/cherry-pick request (GitHub issue or Microsoft ADO):
Failure type:
Tested branch
Test result
master, head 9031ac764 :
• Unit tests: CLI 402 passed; dhcp-utilities 437 passed
• End-to-end (KVM vms-kvm-t0, image patched to 0b7d65fe5 ): automated tests are sonic-net/sonic-mgmt#29054; the test plan is #28933.
• F: 34 passed, 1 skipped (F14, not applicable with the SONiC relay), 1 failed. The failure was F01 related to ISC relay restart, F01 passed 2/2 on rerun.
• C 36/36, V 11/11, L 16/16, M 4/4, S 4/4.
• On the switch, redis-cli monitor confirmed binding update sends MULTI / DEL / HSET / EXEC .
• 9031ac764 on the same testbed: the overlapping force-delete/recreate scenario is rejected (exit 2, no range written), and a valid recreate is applied with Kea running
Description for the changelog
[dhcp_server] Add MATCH mode to dhcpservd: compile DHCP_SERVER_IPV4_MATCH/BINDING into Kea client classes and pools (Option 82 circuit-id / Option 60), with validated, atomic config activation.
Link to config_db schema for YANG module changes
https://github.com/sonic-net/sonic-buildimage/blob/master/src/sonic-yang-models/doc/Configuration.md#dhcp_server_ipv4
A picture of a cute animal (not mandatory but encouraged)