- 
                Notifications
    You must be signed in to change notification settings 
- Fork 81
Implement a strategy to handle OOM in direct memory #475
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
          
     Draft
      
      
            andsel
  wants to merge
  19
  commits into
  logstash-plugins:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
andsel:mitigate_thundering_herd_2
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Draft
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            19 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      dc8a8b0
              
                Avoid to run Beats parser and Beats protocol handler in separate exec…
              
              
                andsel 700543c
              
                Ported core part of original #410 PR
              
              
                andsel 8e5f7b3
              
                Added pull way of fetching data
              
              
                andsel dbabb78
              
                Extracted the pull mode part into a separate handler
              
              
                andsel ea7f14d
              
                Update the flow control handler to avoid new reads if the channel bec…
              
              
                andsel 234569d
              
                Separated the logic to drop incoming connections into specific handler
              
              
                andsel 86e4445
              
                Fist draft of the integration test
              
              
                andsel 0148987
              
                Removed tests using EmbeddedChannel because doesn't manage the writea…
              
              
                andsel af04733
              
                Reshaped the asynch code to be more linear
              
              
                andsel cd7aafe
              
                Covered the number of connection limiter with unit test
              
              
                andsel c6e775c
              
                Pessimistic remediation, when a direct OOM happens close the channel
              
              
                andsel e34bf25
              
                Removed from the log string any reference to Filebeat
              
              
                andsel 7a6982e
              
                Raised up the log level level when dropping connections becuase of th…
              
              
                andsel 299ee27
              
                Better actionable suggestion to user in case of OOM
              
              
                andsel e24f339
              
                Updated OOMConnectionCloser to monitor the consumption of memory also…
              
              
                andsel c7c54d9
              
                Re-introduce the beats handlers worker group to separata the Beats pr…
              
              
                andsel 16a76b8
              
                Added feature flag named protect_direct_memory to control the usage o…
              
              
                andsel d75a0df
              
                Throw a configuration error if Netty reserved direct memory is not an…
              
              
                andsel 68f4967
              
                Add missed shutdown of beat's worker loop
              
              
                andsel File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| package org.logstash.beats; | ||
|  | ||
| import io.netty.channel.Channel; | ||
| import io.netty.channel.ChannelHandler.Sharable; | ||
| import io.netty.channel.ChannelHandlerContext; | ||
| import io.netty.channel.ChannelInboundHandlerAdapter; | ||
| import org.apache.logging.log4j.LogManager; | ||
| import org.apache.logging.log4j.Logger; | ||
|  | ||
| /** | ||
| * Configure the channel where it's installed to operate the reads in pull mode, | ||
| * disabling the autoread and explicitly invoking the read operation. | ||
| * The flow control to keep the outgoing buffer under control is done | ||
| * avoiding to read in new bytes if the outgoing direction became not writable, this | ||
| * excert back pressure to the TCP layer and ultimately to the upstream system. | ||
| * */ | ||
| @Sharable | ||
| public final class FlowLimiterHandler extends ChannelInboundHandlerAdapter { | ||
|  | ||
| private final static Logger logger = LogManager.getLogger(FlowLimiterHandler.class); | ||
|  | ||
| @Override | ||
| public void channelRegistered(final ChannelHandlerContext ctx) throws Exception { | ||
| ctx.channel().config().setAutoRead(false); | ||
| super.channelRegistered(ctx); | ||
| } | ||
|  | ||
| @Override | ||
| public void channelActive(final ChannelHandlerContext ctx) throws Exception { | ||
| super.channelActive(ctx); | ||
| if (isAutoreadDisabled(ctx.channel()) && ctx.channel().isWritable()) { | ||
| ctx.channel().read(); | ||
| } | ||
| } | ||
|  | ||
| @Override | ||
| public void channelReadComplete(final ChannelHandlerContext ctx) throws Exception { | ||
| super.channelReadComplete(ctx); | ||
| if (isAutoreadDisabled(ctx.channel()) && ctx.channel().isWritable()) { | ||
| ctx.channel().read(); | ||
| } | ||
| } | ||
|  | ||
| private boolean isAutoreadDisabled(Channel channel) { | ||
| return !channel.config().isAutoRead(); | ||
| } | ||
|  | ||
| @Override | ||
| public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { | ||
| ctx.channel().read(); | ||
| super.channelWritabilityChanged(ctx); | ||
|  | ||
| logger.debug("Writability on channel {} changed to {}", ctx.channel(), ctx.channel().isWritable()); | ||
| } | ||
|  | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| package org.logstash.beats; | ||
|  | ||
| import io.netty.buffer.ByteBufAllocator; | ||
| import io.netty.buffer.PooledByteBufAllocator; | ||
| import io.netty.channel.ChannelHandlerContext; | ||
| import io.netty.channel.ChannelInboundHandlerAdapter; | ||
| import io.netty.util.ReferenceCountUtil; | ||
| import io.netty.util.internal.PlatformDependent; | ||
| import org.apache.logging.log4j.LogManager; | ||
| import org.apache.logging.log4j.Logger; | ||
|  | ||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
|  | ||
| public class OOMConnectionCloser extends ChannelInboundHandlerAdapter { | ||
|  | ||
| private final PooledByteBufAllocator allocator; | ||
|  | ||
| static class DirectMemoryUsage { | ||
| final long used; | ||
| final long pinned; | ||
| private final PooledByteBufAllocator allocator; | ||
| final short ratio; | ||
|  | ||
| private DirectMemoryUsage(long used, long pinned, PooledByteBufAllocator allocator) { | ||
| this.used = used; | ||
| this.pinned = pinned; | ||
| this.allocator = allocator; | ||
| this.ratio = (short) Math.round(((double) pinned / used) * 100); | ||
| } | ||
|  | ||
| static DirectMemoryUsage capture(PooledByteBufAllocator allocator) { | ||
| long usedDirectMemory = allocator.metric().usedDirectMemory(); | ||
| long pinnedDirectMemory = allocator.pinnedDirectMemory(); | ||
| return new DirectMemoryUsage(usedDirectMemory, pinnedDirectMemory, allocator); | ||
| } | ||
|  | ||
| boolean isCloseToOOM() { | ||
| long maxDirectMemory = PlatformDependent.maxDirectMemory(); | ||
| int chunkSize = allocator.metric().chunkSize(); | ||
| return ((maxDirectMemory - used) <= chunkSize) && ratio > 75; | ||
| } | ||
| } | ||
|  | ||
| private final static Logger logger = LogManager.getLogger(OOMConnectionCloser.class); | ||
|  | ||
| public static final Pattern DIRECT_MEMORY_ERROR = Pattern.compile("^Cannot reserve \\d* bytes of direct buffer memory.*$"); | ||
|  | ||
| OOMConnectionCloser() { | ||
| allocator = (PooledByteBufAllocator) ByteBufAllocator.DEFAULT; | ||
| } | ||
|  | ||
| @Override | ||
| public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { | ||
| DirectMemoryUsage direct = DirectMemoryUsage.capture(allocator); | ||
| logger.info("Direct memory status, used: {}, pinned: {}, ratio: {}", direct.used, direct.pinned, direct.ratio); | ||
| if (direct.isCloseToOOM()) { | ||
| logger.warn("Closing connection {} because running out of memory, used: {}, pinned: {}, ratio {}", ctx.channel(), direct.used, direct.pinned, direct.ratio); | ||
| ReferenceCountUtil.release(msg); // to free the memory used by the buffer | ||
| ctx.flush(); | ||
| ctx.close(); | ||
| } else { | ||
| super.channelRead(ctx, msg); | ||
| } | ||
| } | ||
|  | ||
| @Override | ||
| public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { | ||
| if (isDirectMemoryOOM(cause)) { | ||
| DirectMemoryUsage direct = DirectMemoryUsage.capture(allocator); | ||
| logger.info("Direct memory status, used: {}, pinned: {}, ratio: {}", direct.used, direct.pinned, direct.ratio); | ||
| logger.warn("Dropping connection {} due to lack of available Direct Memory. Please lower the number of concurrent connections or reduce the batch size. " + | ||
| "Alternatively, raise -XX:MaxDirectMemorySize option in the JVM running Logstash", ctx.channel()); | ||
| ctx.flush(); | ||
| ctx.close(); | ||
| } else { | ||
| super.exceptionCaught(ctx, cause); | ||
| } | ||
| } | ||
|  | ||
| private boolean isDirectMemoryOOM(Throwable th) { | ||
| if (!(th instanceof OutOfMemoryError)) { | ||
| return false; | ||
| } | ||
| Matcher m = DIRECT_MEMORY_ERROR.matcher(th.getMessage()); | ||
| return m.matches(); | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd like us to be a bit more intentional in why we're removing the executor group here. in my test PR I removed it to simplify the number of threads I had to reason about, and having a single pool for both boss/worker loops would mean blocking the workers would stop boss from accepting new connections too.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't be the complete pipeline executed in the worker group, instead just BeatsParser and BeatsHandler, while BeatsHacker and Connectionhandler are still executed by the boss group?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I mean shouldn't use the
ServerBootstrap.group(bossGroup, workerGroup)instead of assigning the group for just those 2 Beats handler? If we do this, we have at least one thread context switch on every pipeline. Maybe it's something I'm not grasping.