GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Memory leak when using SslHandler · Issue #13698 · netty/netty

Memory leak when using SslHandler #13698

New issue
Copy link
New issue
Copy link
Closed
Closed
Memory leak when using SslHandler#13698
Copy link

Description

@JaquierM
JaquierM
opened on Nov 15, 2023
Issue body actions

Expected behavior

No memory leak.

Actual behavior

When a connection is open, we send data and the ram usage increase depending on the size of the data.

The java heap stay in a correct range (500 - 1000 Mb) but the process ram is increasing for each request (approximately by the size of the send payload).

The problem source is probably the off-heap allocation but even with the option -Dio.netty.leakDetectionLevel=PARANOID no error are shown.

When disabling the .addLast(sslCtx.newHandler(ch.alloc())), the leak disappear.

Steps to reproduce

  1. Create a SslContext for a server with a crt, key and ca.
  2. Bootstrap a server
  3. Initialize a channel with :
  • sslHandler
  • ChannelInboundHandlerAdapter that send the data and close the channel
  1. Send some requests with wget for example
  2. The ram used should increase

Minimal yet complete reproducer code (or URL to code)

  1. Generate a random data file.
dd if=/dev/urandom of=/tmp/random1G.bin bs=1G count=1 status=progress
  1. Launch the server to send the data upon request.
package org.example

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class Main {

    static final int PORT = Integer.parseInt(System.getProperty("port", "2222"));

    public static void main(String[] args) throws Exception {

        SelfSignedCertificate selfSignedCertificate = new SelfSignedCertificate("test");
        SslContext sslCtx = SslContextBuilder
            .forServer(selfSignedCertificate.certificate(), selfSignedCertificate.privateKey())
            .clientAuth(ClientAuth.OPTIONAL)
            .protocols(new String[] {"TLSv1.3"})
            .build();

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline()
                            .addLast(sslCtx.newHandler(ch.alloc()))
                            .addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(final ChannelHandlerContext ctx) {
                                    try {
                                        byte[] datas = new FileInputStream("/tmp/random1G.bin").readAllBytes();

                                        ByteBuf buffer = ctx.alloc().buffer(datas.length);
                                        buffer.writeBytes(datas);

                                        ctx.writeAndFlush(buffer).addListener(f -> ctx.close());
                                    } catch (IOException e) {
                                        System.out.println("closing " + e.getMessage());
                                        ctx.close();
                                    }
                                }
                            })
                            .addLast(new ChannelDuplexHandler() {
                                @Override
                                public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
                                    ctx.close();
                                }
                            });
                    }
                });

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

Netty version

6.1.101.Final

JVM version (e.g. java -version)

openjdk 17.0.2 2022-01-18
OpenJDK Runtime Environment GraalVM CE 22.0.0.2 (build 17.0.2+8-jvmci-22.0-b05)
OpenJDK 64-Bit Server VM GraalVM CE 22.0.0.2 (build 17.0.2+8-jvmci-22.0-b05, mixed mode, sharing)

OS version (e.g. uname -a)

Linux workstation 6.5.0-2-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.5.6-1 (2023-10-07) x86_64 GNU/Linux

Activity

  1. hyperxpro commented on Nov 15, 2023

    @hyperxpro
    hyperxpro
    on Nov 15, 2023
    Contributor
    More actions

    How big is your payload? What is the transfer speed? Which cipher are you exactly using?

  2. JaquierM commented on Nov 15, 2023

    @JaquierM
    JaquierM
    on Nov 15, 2023
    Author
    More actions

    The payload was around 1GB when we detected the problem but it is present with smaller payload (200MB).
    On my machine, the speed is around 900MB/s.
    The cipher suite is TLS_AES_128_GCM_SHA256.

  3. hyperxpro commented on Nov 15, 2023

    @hyperxpro
    hyperxpro
    on Nov 15, 2023
    Contributor
    More actions

    1 GB+ of memory usage seems fine.

    Also, you're reading all data into byte[] and it will indeed result in larger heap usage, and GC will not immediately kick in.

  4. chrisvest commented on Nov 15, 2023

    @chrisvest
    chrisvest
    on Nov 15, 2023
    Member
    More actions

    A few suggestions:

    1. Transport the file using a sequence of smaller buffers, and look out for channel writability – this allow our pooling buffer allocator to help you more.
    2. Switch to using the native epoll transport, and tcnative-boringssl-static TLS implementation – this will let your pipeline use off-heap buffers throughout, so there's no need to copy data between heap and native memory.
    3. Open your file with FileChannel instead of FileInputStream – this API lets you do file IO with off-heap buffers as well.
    4. Allocate buffers using the ByteBufAllocator.ioBuffer(int) method, and read the file data using ByteBuf.writeBytes(FileChannel, position, length) – for actually doing the efficient off-heap file IO.
  5. JaquierM commented on Nov 16, 2023

    @JaquierM
    JaquierM
    on Nov 16, 2023
    Author
    More actions

    I was able to solve my problem. It was a misunderstanding of how buffers work (pool with SSL) and a misuse of Netty.

    By using a ChunkedFile, the leak is gone.

    Thanks a lot for your help.

  6. JaquierM
    closed this as completedon Nov 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402775 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.