Skip to content

add ipsec controller unit test#1461

Merged
kmesh-bot merged 6 commits intokmesh-net:mainfrom
zrggw:ipsec_controller_test
Aug 4, 2025
Merged

add ipsec controller unit test#1461
kmesh-bot merged 6 commits intokmesh-net:mainfrom
zrggw:ipsec_controller_test

Conversation

@zrggw
Copy link
Copy Markdown
Contributor

@zrggw zrggw commented Jul 30, 2025

What type of PR is this?
/kind enhancement
/kind security

What this PR does / why we need it:
Add ipsec controller unit test.
Main content introduction as follows:

  1. TestNewIPsecController: Tests IPsec controller initialization including:

    • Successful instance creation with proper environment setup
    • Failure scenarios when required environment variables are missing
  2. TestHandleKNIEvents: Validates KmeshNodeInfo event handling logic including:

    • handleKNIAdd: Tests adding remote nodes to workqueue while ignoring local nodes
    • handleKNIUpdate: Verifies no queue addition for unchanged specs and SPI field updates triggering queue addition
  3. TestMapOperations: Tests BPF map operations including:

    • CIDR address add/delete operations
  4. TestNodeOperations: Validates node synchronization functionality including:

    • Local node info creation/update
    • All node info synchronization
    • Xfrm rule and KNI map association with handleOneNodeInfo
  5. TestProcessNextItem: Validates workqueue processing logic including:

    • Normal node processing flow
    • Handling non-existent nodes
    • Function handleOneNodeInfo error in function processNextItem and retry mechanisms (within and beyond retry limits)
  6. TestHandleTc: Validates the IPsec controller's TC (Traffic Control) program attachment/detachment logic

changes in ipsec_controller.go

  1. Fixed a bug in processNextItem function a bug may exist in the processNextItem function in ipsec_controller.go. #1462
  2. Added error handling for WithNetNSPath in handleKNIDelete to ensure consistency between KNIMap and xfrm states/policies

Which issue(s) this PR fixes:
Fixes #

Special notes for your reviewer:

Does this PR introduce a user-facing change?:


zrggw added 2 commits July 30, 2025 17:48
Signed-off-by: aicee <hhbin2000@foxmail.com>
Signed-off-by: aicee <hhbin2000@foxmail.com>
@kmesh-bot kmesh-bot added the kind/enhancement New feature or request label Jul 30, 2025
@kmesh-bot kmesh-bot requested a review from kwb0523 July 30, 2025 10:08
@kmesh-bot kmesh-bot requested a review from YaoZengzeng July 30, 2025 10:08
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @zrggw, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new, comprehensive suite of unit tests for the IPsec controller. These tests cover critical aspects of the controller's lifecycle and functionality, including initialization, event handling, BPF map interactions, node synchronization, and workqueue processing. The addition of these tests significantly enhances the reliability, stability, and maintainability of the IPsec controller component.

Highlights

  • IPsec Controller Initialization Tests: Added unit tests for the NewIPsecController function, covering successful controller creation with proper environment setup and failure scenarios when required environment variables are missing.
  • KmeshNodeInfo Event Handling Tests: Implemented tests for handleKNIAdd and handleKNIUpdate functions, validating the logic for adding remote nodes to the workqueue, ignoring local nodes, and triggering queue additions for relevant SPI field updates.
  • BPF Map Operations Tests: Included tests for BPF map operations, specifically focusing on the correct addition and deletion of CIDR addresses within the KNI map.
  • Node Synchronization Functionality Tests: Developed tests to validate the controller's node synchronization capabilities, including the creation and update of local KmeshNodeInfo, synchronization of all node information, and the association of Xfrm rules and KNI maps via handleOneNodeInfo.
  • Workqueue Processing Logic Tests: Added comprehensive tests for the processNextItem function, ensuring proper handling of normal node processing flow, non-existent nodes, and robust retry mechanisms for errors encountered during handleOneNodeInfo.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@zrggw
Copy link
Copy Markdown
Contributor Author

zrggw commented Jul 30, 2025

cc @hzxuzhonghu

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds a comprehensive suite of unit tests for the IPsec controller, a valuable enhancement for ensuring code quality and security. The tests cover controller initialization, event handling, BPF map operations, node synchronization, and workqueue processing. My review focuses on improving the reliability and correctness of these new tests by addressing potential flakiness, improving test coverage with negative cases, and correcting logic in the retry mechanism tests.

Comment on lines +571 to +580
// Create local node info
controller.knclient.Create(context.TODO(), &controller.kmeshNodeInfo, metav1.CreateOptions{})
// controller.updateLocalKmeshNodeInfo()
assert.NoError(t, err)

time.Sleep(time.Second)

result := controller.processNextItem()
assert.True(t, result) // Should still return true
assert.Equal(t, 0, controller.queue.NumRequeues("test-local-node"))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

This test has several critical issues:

  1. Incorrect Error Check: On line 574, assert.NoError(t, err) checks the err variable from an outer scope, not the result of the Create call on line 572. The error returned by Create is ignored.
  2. Unnecessary time.Sleep: The time.Sleep(time.Second) on line 576 is not needed and slows down the test suite. Cache synchronization is handled before this test runs.
  3. Flawed Test Logic: The test name implies it checks the retry mechanism, but it only processes the item once. The assertion on line 580, assert.Equal(t, 0, controller.queue.NumRequeues(...)), is misleading because the controller's processNextItem has a bug where it calls Forget() even after re-queuing, which resets the retry counter. A correct test should assert that NumRequeues becomes 1 after the first failed attempt.
  4. Dead Code: Line 573 is a commented-out line that should be removed.

Please refactor this test to correctly check the error, remove the sleep and dead code, and properly validate the retry behavior.

// Create local node info so the lister can find it
		_, err := controller.knclient.Create(context.TODO(), &controller.kmeshNodeInfo, metav1.CreateOptions{})
		require.NoError(t, err)

		result := controller.processNextItem()
		assert.True(t, result) // Should still return true

		// A correct retry implementation would re-queue the item on failure.
		// This assertion reflects that expectation and will help catch regressions or bugs in the controller.
		assert.Equal(t, 1, controller.queue.NumRequeues("test-local-node"))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding point 3 "is misleading because the controller's processNextItem has a bug where it calls Forget() even after re-queuing, which resets the retry counter. ", I have created an issue on #1462

@codecov
Copy link
Copy Markdown

codecov bot commented Jul 30, 2025

Codecov Report

❌ Patch coverage is 70.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 38.35%. Comparing base (65d8180) to head (7a9dffa).
⚠️ Report is 17 commits behind head on main.

Files with missing lines Patch % Lines
...kg/controller/encryption/ipsec/ipsec_controller.go 70.00% 2 Missing and 1 partial ⚠️
Files with missing lines Coverage Δ
...kg/controller/encryption/ipsec/ipsec_controller.go 47.92% <70.00%> (+47.92%) ⬆️

... and 1 file with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 76e80d1...7a9dffa. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…dd TestHandleTc

Signed-off-by: aicee <hhbin2000@foxmail.com>
@zrggw
Copy link
Copy Markdown
Contributor Author

zrggw commented Jul 31, 2025

What's new:

  1. Fixed codespell errors and problems mentioned by genimi
  2. Fixed a bug in processNextItem function a bug may exist in the processNextItem function in ipsec_controller.go. #1462
  3. Added error handling for WithNetNSPath in handleKNIDelete to ensure consistency between KNIMap and xfrm states/policies
  4. Added TestHandleTc test cases for TC program attachment/detachment validation

@zrggw
Copy link
Copy Markdown
Contributor Author

zrggw commented Jul 31, 2025

/gemini review

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The code changes introduce unit tests for the IPsec controller. There's a critical bug in the IPsec resource cleanup logic that needs to be fixed. Also, there are a couple of issues in the new tests that should be addressed.

zrggw added 2 commits July 31, 2025 18:56
Signed-off-by: aicee <hhbin2000@foxmail.com>
Copilot AI review requested due to automatic review settings August 1, 2025 01:45
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds comprehensive unit tests for the IPsec controller while fixing a bug in the processNextItem function. The tests ensure proper validation of IPsec controller functionality including initialization, event handling, BPF map operations, and traffic control program management.

  • Adds extensive unit test coverage for IPsec controller functionality
  • Fixes missing return statement bug in processNextItem function
  • Adds error handling for network namespace operations in handleKNIDelete

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
pkg/controller/encryption/ipsec/ipsec_controller_test.go New comprehensive test suite covering controller initialization, event handling, map operations, node synchronization, and TC program management
pkg/controller/encryption/ipsec/ipsec_controller.go Bug fix in processNextItem and improved error handling in handleKNIDelete

Signed-off-by: aicee <hhbin2000@foxmail.com>
log.Errorf("failed to handle other node %s err: %v, giving up", name, err)
c.queue.Forget(key)
}
return true
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Copy Markdown
Member

@hzxuzhonghu hzxuzhonghu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/lgtm

@kmesh-bot
Copy link
Copy Markdown
Collaborator

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: hzxuzhonghu

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@kmesh-bot kmesh-bot merged commit aa23e55 into kmesh-net:main Aug 4, 2025
12 checks passed
@zrggw zrggw deleted the ipsec_controller_test branch August 4, 2025 07:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants