Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ProtocolCodeBasedDecoder memory leak #355

Closed
wants to merge 4 commits into from

Conversation

JoeCqupt
Copy link
Contributor

@JoeCqupt JoeCqupt commented Jul 26, 2024

reproduce code

    @Test
    public void testDecodeIllegalPacket2() {
        EmbeddedChannel channel = new EmbeddedChannel();
        ProtocolCodeBasedDecoder decoder = new ProtocolCodeBasedDecoder(1);
        channel.pipeline().addLast(decoder);

        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(8);
        byteBuf.writeByte((byte) 13);

        int readerIndex = byteBuf.readerIndex();
      
        Assert.assertEquals(0, readerIndex);
        Exception exception = null;
        try {
            channel.writeInbound(byteBuf);
        } catch (Exception e) {
            // ignore
            exception = e;
        }
        Assert.assertNotNull(exception);
        Assert.assertTrue(byteBuf.refCnt() == 0);
    }

when ProtocolCodeBasedDecoder#decode() throw exception . ByteBuf param not released

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for decoding processes, improving robustness against unexpected input.
    • Introduced a new test case to improve coverage for decoder interactions with illegal packets.
  • Bug Fixes

    • Ensured consistent state of the buffer after exception handling during decoding operations.

@sofastack-cla sofastack-cla bot added bug Something isn't working cla:yes size/M labels Jul 26, 2024
Copy link

coderabbitai bot commented Jul 26, 2024

Walkthrough

The changes enhance the error handling and readability of the decode method in the ProtocolCodeBasedDecoder class. Key improvements include restructuring the try-finally block for better buffer index management and adding explicit checks for null protocol objects. The test suite for the decoder is also strengthened with new tests that confirm proper behavior when illegal packets are processed, ensuring robust performance under error conditions.

Changes

Files Change Summary
src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java
src/test/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoderTest.java
The decoder's decode method is modified for improved error handling and clarity, with added checks for null protocol objects. The test suite is updated with enhanced tests to validate decoder behavior for illegal packets, including checks on ByteBuf state.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Decoder
    participant ByteBuf

    Client->>Decoder: Send data
    Decoder->>ByteBuf: Process data
    ByteBuf->>Decoder: Check for errors
    alt No error
        Decoder->>Client: Return decoded data
    else Error occurred
        ByteBuf->>Decoder: Reset reader index
        Decoder->>Client: Throw CodecException
    end
Loading

🐇 Through the code, we hop and play,
With tweaks that brighten the day!
Errors handled, tests anew,
Our decoder shines, it’s tried and true!
So let’s all cheer, hip-hip-hooray!
For robust code that’s here to stay! 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 12ef565 and 3500acb.

Files selected for processing (2)
  • src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java (1 hunks)
  • src/test/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoderTest.java (3 hunks)
Additional comments not posted (18)
src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java (9)

82-82: Mark reader index before decoding.

Marking the reader index at the beginning ensures that the buffer can be reset to this position in case of an error or incomplete packet.


83-84: Initialize protocolCode and protocol.

Initializing protocolCode and protocol before the try block ensures they are available for use within the finally block.


86-89: Handle null protocolCode.

Returning early if protocolCode is null prevents further processing of an incomplete or invalid packet.


92-97: Set protocol and version attributes.

Setting the protocol and version attributes if they are not already set ensures that the channel has the correct protocol information.


100-101: Retrieve protocol from ProtocolManager.

Retrieving the protocol from ProtocolManager based on the decoded protocolCode.


102-104: Reset reader index in finally block.

Resetting the reader index before throwing an exception or decoding content ensures that the buffer is in a consistent state.


107-110: Throw CodecException for unknown protocol.

Throwing a CodecException if the protocol is null ensures that unknown protocols are handled appropriately.


112-112: Delegate decoding to protocol decoder.

Delegating the decoding to the protocol's decoder ensures that the specific protocol's decoding logic is used.


113-116: Skip readable bytes and rethrow exception.

Skipping the readable bytes and rethrowing the exception ensures that the buffer is cleared and the exception is propagated.

src/test/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoderTest.java (9)

56-56: Capture readable bytes before decoding.

Capturing the number of readable bytes before decoding ensures that the buffer state can be validated after an exception.


70-71: Assert readerIndex after exception.

Asserting that the readerIndex remains consistent after an exception ensures that the buffer state is correctly maintained.


73-73: Add new test method testDecodeIllegalPacket2.

The new test method enhances the test coverage for the decoder's behavior when handling illegal packets.


75-77: Set up EmbeddedChannel and add decoder.

Setting up an EmbeddedChannel and adding the decoder to its pipeline ensures that the decoder is tested in a realistic environment.


79-81: Write byte to ByteBuf.

Writing a byte to the ByteBuf simulates an illegal packet for the decoder to process.


82-83: Capture reader index and readable bytes.

Capturing the readerIndex and readableBytes before writing to the channel ensures that the buffer state can be validated after an exception.


85-91: Write ByteBuf to channel and capture exception.

Writing the ByteBuf to the channel and capturing any exceptions ensures that the decoder's error handling is tested.


92-94: Assert readerIndex after exception.

Asserting that the readerIndex remains consistent after an exception ensures that the buffer state is correctly maintained.


96-96: Assert ByteBuf reference count is zero.

Asserting that the ByteBuf reference count is zero ensures that the memory leak has been resolved.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3500acb and d94c69b.

Files selected for processing (1)
  • src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java

@JoeCqupt
Copy link
Contributor Author

JoeCqupt commented Jul 26, 2024

这个CI好像有问题,线下跑的单测一点问题没有,CI跑就报错
线下:
image
CI:
https://github.com/sofastack/sofa-bolt/actions/runs/10111851447/job/27964641532?pr=355#step:5:1442
image

@JoeCqupt JoeCqupt changed the title Fix ProtocolCodeBasedDecoder.java memory leak Fix ProtocolCodeBasedDecoder memory leak Jul 26, 2024
@funky-eyes
Copy link
Contributor

这个CI好像有问题,线下跑的单测一点问题没有,CI跑就报错 线下: image CI: https://github.com/sofastack/sofa-bolt/actions/runs/10111851447/job/27964641532?pr=355#step:5:1442 image

我跟你有相同的问题

@JoeCqupt
Copy link
Contributor Author

JoeCqupt commented Aug 9, 2024

@chuailiwu

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d94c69b and 5399f37.

Files selected for processing (1)
  • src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java (1 hunks)
Additional comments not posted (9)
src/main/java/com/alipay/remoting/codec/ProtocolCodeBasedDecoder.java (9)

82-82: Mark reader index before decoding.

Marking the reader index before decoding ensures that the buffer can be reset to this position if decoding fails. This is a good practice for maintaining the integrity of the buffer state.

The code changes are approved.


83-84: Initialize protocolCode and protocol variables.

Initializing these variables at the beginning of the try block ensures they are available throughout the block. This is a good practice for clarity and scope management.

The code changes are approved.


86-90: Check for null protocolCode.

The check for protocolCode == null ensures that the method returns early if the protocol code cannot be decoded. This prevents further processing of an invalid buffer.

The code changes are approved.


92-97: Set protocol and version attributes.

Setting the protocol and version attributes on the channel ensures that the correct protocol and version are used for subsequent processing. This is a good practice for maintaining protocol consistency.

The code changes are approved.


100-101: Retrieve protocol from ProtocolManager.

Retrieving the protocol from ProtocolManager ensures that the correct protocol is used for decoding. This is a good practice for modularity and reusability.

The code changes are approved.


102-104: Reset reader index in finally block.

Resetting the reader index in the finally block ensures that the buffer state is restored before any exceptions are thrown or content is decoded. This is a good practice for maintaining buffer integrity.

The code changes are approved.


107-110: Check for null protocol and throw exception.

The check for protocol == null and throwing a CodecException ensures that any unknown protocol codes are handled appropriately. This is a good practice for robust error handling.

The code changes are approved.


112-113: Delegate decoding to protocol decoder.

Delegating the decoding to the protocol's decoder ensures that the correct decoding logic is used for the protocol. This is a good practice for modularity and reusability.

The code changes are approved.


114-116: Skip readable bytes and rethrow exception.

Skipping the readable bytes and rethrowing the exception ensures that the buffer is cleared and the exception is propagated. This is a good practice for maintaining buffer integrity and proper error handling.

The code changes are approved.

@OrezzerO
Copy link
Collaborator

Hi, @JoeCqupt , I doubt if it is a bug of bolt. ByteBuf will be released at channelInactive method. I think you need to check in what condition (such as you encounter an exception when decoding but not close the connection ) you did not invoke this method.

@JoeCqupt JoeCqupt closed this Aug 30, 2024
@JoeCqupt
Copy link
Contributor Author

Hi, @JoeCqupt , I doubt if it is a bug of bolt. ByteBuf will be released at channelInactive method. I think you need to check in what condition (such as you encounter an exception when decoding but not close the connection ) you did not invoke this method.

yep. you are right.
This modification is optional

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working cla:yes size/M
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants