io.netty.util.ResourceLeakDetector Java Examples

The following examples show how to use io.netty.util.ResourceLeakDetector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ArchaiusServerTest.java    From riposte with Apache License 2.0 7 votes vote down vote up
@Test
public void verify_essential_behavior() throws Exception {
    // given
    setAppAndEnvironment("archaiusserver", "compiletimetest");
    int port = findFreePort();
    ArchaiusServer server = generateArchaiusServer(port);
    assertThat(System.getProperty("org.jboss.logging.provider")).isNull();

    // when
    server.launchServer(null);
    ExtractableResponse<Response> response =
        given()
            .baseUri("http://localhost")
            .port(port)
            .when()
            .get(SomeEndpoint.MATCHING_PATH)
            .then()
            .extract();

    // then
    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(response.asString()).isEqualTo("overridevalue");
    assertThat(System.getProperty("org.jboss.logging.provider")).isEqualTo("slf4j");
    assertThat(ResourceLeakDetector.getLevel()).isEqualTo(ResourceLeakDetector.Level.PARANOID);
}
 
Example #2
Source File: MqttTransportService.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() throws Exception {
  log.info("Setting resource leak detector level to {}", leakDetectorLevel);
  ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

  log.info("Starting MQTT transport...");
  log.info("Lookup MQTT transport adaptor {}", adaptorName);
  // this.adaptor = (MqttTransportAdaptor) appContext.getBean(adaptorName);

  log.info("Starting MQTT transport server");
  bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
  workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.TCP_NODELAY, true)
      .childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
      .childHandler(new MqttTransportServerInitializer(msgProducer, deviceService, authService, assetService,
          assetAuthService, relationService, sslHandlerProvider));

  serverChannel = b.bind(host, port).sync().channel();
  log.info("Mqtt transport started: {}:{}!", host, port);
}
 
Example #3
Source File: NettyServer.java    From netty-learning-example with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() throws Exception {
        log.info("Setting resource leak detector level to {}",leakDetectorLevel);
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

        log.info("Starting Server");
        //创建boss线程组 用于服务端接受客户端的连接
        bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
        // 创建 worker 线程组 用于进行 SocketChannel 的数据读写
        workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
        // 创建 ServerBootstrap 对象
        ServerBootstrap b = new ServerBootstrap();
        //设置使用的EventLoopGroup
        b.group(bossGroup, workerGroup)
                //设置要被实例化的为 NioServerSocketChannel 类
                .channel(NioServerSocketChannel.class)
                // 设置 NioServerSocketChannel 的处理器
                .handler(new LoggingHandler(LogLevel.INFO))
                // 设置连入服务端的 Client 的 SocketChannel 的处理器
                .childHandler(new NettyServerInitializer());
        // 绑定端口,并同步等待成功,即启动服务端
        channelFuture = b.bind(port).sync();

        log.info("Server started!");

}
 
Example #4
Source File: TestClient.java    From jkcp with Apache License 2.0 6 votes vote down vote up
/**
 * tcpdump udp port 2225 -x -vv -s0 -w 1112.pcap
 *
 * @param args
 * @throws java.lang.InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);
    TestClient tc = new TestClient();
    tc.noDelay(1, 20, 2, 1);
    tc.setMinRto(10);
    tc.wndSize(32, 32);
    tc.setTimeout(10 * 1000);
    tc.setMtu(512);
    // tc.setConv(121106);//默认conv随机

    tc.connect(new InetSocketAddress("localhost", 2222));
    tc.start();
    String content = "sdfkasd你好。。。。。。。";
    ByteBuf bb = PooledByteBufAllocator.DEFAULT.buffer(1500);
    bb.writeBytes(content.getBytes(Charset.forName("utf-8")));
    tc.send(bb);
}
 
Example #5
Source File: RestClientBenchmark.java    From turbo-rpc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	ResourceLeakDetector.setLevel(Level.DISABLED);
	// CtClass.debugDump = "d:/debugDump";

	// RestClientBenchmark clientBenchmark = new RestClientBenchmark();
	// System.out.println(clientBenchmark.createUser());
	// clientBenchmark.close();

	Options opt = new OptionsBuilder()//
			.include(RestClientBenchmark.class.getSimpleName())//
			.warmupIterations(5)//
			.measurementIterations(5)//
			.threads(CONCURRENCY)//
			.forks(1)//
			.build();

	new Runner(opt).run();
}
 
Example #6
Source File: TypesafeConfigServerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_essential_behavior() throws Exception {
    // given
    setAppAndEnvironment("typesafeconfigserver", "compiletimetest");
    int port = findFreePort();
    TypesafeConfigServer server = generateTypesafeConfigServer(port);
    assertThat(System.getProperty("org.jboss.logging.provider")).isNull();

    // when
    server.launchServer(null);
    ExtractableResponse<Response> response =
        given()
            .baseUri("http://localhost")
            .port(port)
        .when()
            .get(SomeEndpoint.MATCHING_PATH)
        .then()
            .extract();

    // then
    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(response.asString()).isEqualTo("overridevalue");
    assertThat(System.getProperty("org.jboss.logging.provider")).isEqualTo("slf4j");
    assertThat(ResourceLeakDetector.getLevel()).isEqualTo(ResourceLeakDetector.Level.PARANOID);
}
 
Example #7
Source File: AbstractByteBufAllocator.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
protected static CompositeByteBuf toLeakAwareBuffer(CompositeByteBuf buf) {
    ResourceLeakTracker<ByteBuf> leak;
    switch (ResourceLeakDetector.getLevel()) {
        case SIMPLE:
            leak = AbstractByteBuf.leakDetector.track(buf);
            if (leak != null) {
                buf = new SimpleLeakAwareCompositeByteBuf(buf, leak);
            }
            break;
        case ADVANCED:
        case PARANOID:
            leak = AbstractByteBuf.leakDetector.track(buf);
            if (leak != null) {
                buf = new AdvancedLeakAwareCompositeByteBuf(buf, leak);
            }
            break;
        default:
            break;
    }
    return buf;
}
 
Example #8
Source File: AbstractByteBufAllocator.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
protected static ByteBuf toLeakAwareBuffer(ByteBuf buf) {
    ResourceLeakTracker<ByteBuf> leak;
    switch (ResourceLeakDetector.getLevel()) {
        case SIMPLE:
            leak = AbstractByteBuf.leakDetector.track(buf);
            if (leak != null) {
                buf = new SimpleLeakAwareByteBuf(buf, leak);
            }
            break;
        case ADVANCED:
        case PARANOID:
            leak = AbstractByteBuf.leakDetector.track(buf);
            if (leak != null) {
                buf = new AdvancedLeakAwareByteBuf(buf, leak);
            }
            break;
        default:
            break;
    }
    return buf;
}
 
Example #9
Source File: AbstractByteBufAllocator.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
protected static ByteBuf toLeakAwareBuffer(ByteBuf buf) {
    ResourceLeak leak;
    switch (ResourceLeakDetector.getLevel()) {
        case SIMPLE:
            leak = AbstractByteBuf.leakDetector.open(buf);
            if (leak != null) {
                buf = new SimpleLeakAwareByteBuf(buf, leak);
            }
            break;
        case ADVANCED:
        case PARANOID:
            leak = AbstractByteBuf.leakDetector.open(buf);
            if (leak != null) {
                buf = new AdvancedLeakAwareByteBuf(buf, leak);
            }
            break;
    }
    return buf;
}
 
Example #10
Source File: NettyTcpServer.java    From jt808-netty with MIT License 6 votes vote down vote up
/**
 * 启动Server
 *
 * @throws InterruptedException
 */
@PostConstruct
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(jt808ChannelInitializer)
            .option(ChannelOption.SO_BACKLOG, 1024) //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
            .childOption(ChannelOption.TCP_NODELAY, true)//立即写出
            .childOption(ChannelOption.SO_KEEPALIVE, true);//长连接
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.SIMPLE);//内存泄漏检测 开发推荐PARANOID 线上SIMPLE
    ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
    if (channelFuture.isSuccess()) {
        log.info("TCP服务启动完毕,port={}", this.port);
    }
}
 
Example #11
Source File: NettyTransport.java    From async-gamequery-lib with MIT License 6 votes vote down vote up
public NettyTransport(ChannelType channelType, ExecutorService executor) {
    executorService = executor;
    bootstrap = new Bootstrap();

    //Make sure we have a type set
    if (channelType == null)
        throw new IllegalStateException("No channel type has been specified");

    //Pick the proper event loop group
    if (eventLoopGroup == null) {
        eventLoopGroup = createEventLoopGroup(channelType);
    }

    //Default Channel Options
    addChannelOption(ChannelOption.ALLOCATOR, allocator);
    addChannelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WriteBufferWaterMark.DEFAULT);
    addChannelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

    //Set resource leak detection if debugging is enabled
    if (log.isDebugEnabled())
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);

    //Initialize bootstrap
    bootstrap.group(eventLoopGroup).channel(channelType.getChannelClass());
}
 
Example #12
Source File: NettyTcpServer.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
@Override
protected void config(ServerBootstrap bootstrap) throws Exception{
    super.config(bootstrap);
    if(SystemPropertyUtil.get("io.netty.leakDetectionLevel") == null &&
            SystemPropertyUtil.get("io.netty.leakDetection.level") == null){
        ResourceLeakDetector.setLevel(properties.getResourceLeakDetectorLevel());
    }

    if(SystemPropertyUtil.get("io.netty.maxDirectMemory") == null){
        long maxDirectMemory = -1;
        System.setProperty("io.netty.maxDirectMemory", String.valueOf(maxDirectMemory));
    }
    bootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT,Integer.MAX_VALUE);
    bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(32 * 1024,Integer.MAX_VALUE));
    bootstrap.childOption(ChannelOption.AUTO_CLOSE,true);

    bootstrap.childOption(ChannelOption.TCP_NODELAY, properties.isTcpNodelay());
    for (ServerListener serverListener : serverListeners) {
        serverListener.config(bootstrap);
    }
}
 
Example #13
Source File: IOTMqttServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new MqttTransportServerInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #14
Source File: IOTGatewayServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new GatewayTransportServerInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #15
Source File: CustomProtocolServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new CustomProtocolInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #16
Source File: Server.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);
	try {
		SystemPropertyUtil.setProperty("jupiter.executor.factory.provider.factory_name", "callerRuns");
		SystemPropertyUtil.setProperty("jupiter.executor.factory.affinity.thread", "true");
		SystemPropertyUtil.setProperty("jupiter.tracing.needed", "false");
		JServer server = new DefaultServer().withAcceptor(new JNettyTcpAcceptor(18090, true));
		JConfig config = server.acceptor().configGroup().child();
		config.setOption(JOption.WRITE_BUFFER_HIGH_WATER_MARK, 2048 * 1024);
		config.setOption(JOption.WRITE_BUFFER_LOW_WATER_MARK, 1024 * 1024);
		config.setOption(JOption.SO_RCVBUF, 256 * 1024);
		config.setOption(JOption.SO_SNDBUF, 256 * 1024);

		server.serviceRegistry().provider(new JupiterUserServiceServerImpl()).register();

		server.start(false);
		System.out.println("Jupiter started");
		Thread.sleep(java.lang.Integer.MAX_VALUE);
	} catch (Throwable t) {
		t.printStackTrace();
	}
}
 
Example #17
Source File: TestingPooledByteBufAllocator.java    From drift with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressFBWarnings(value = "DM_GC", justification = "Netty's leak detection only works if buffer is garbage collected")
public void close()
{
    try {
        boolean leaked;
        synchronized (this) {
            leaked = trackedBuffers.stream()
                    .anyMatch(byteBuf -> byteBuf.refCnt() > 0);
            trackedBuffers.clear();
        }
        // Throw an error if there were any leaked buffers
        if (leaked) {
            // Trigger a GC. This will hopefully (but not necessarily) print
            // details about detected leaks to standard error before the error
            // is thrown.
            System.gc();
            throw new AssertionError("LEAK");
        }
    }
    finally {
        ResourceLeakDetector.setLevel(oldLevel);
    }
}
 
Example #18
Source File: NettyTcpTransportTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Ignore("Used for checking for transport level leaks, my be unstable on CI.")
@Test(timeout = 60 * 1000)
public void testSendToClosedTransportFailsButDoesNotLeak() throws Exception {
    Transport transport = null;

    ResourceLeakDetector.setLevel(Level.PARANOID);

    try (NettyEchoServer server = createEchoServer(createServerOptions())) {
        server.start();

        int port = server.getServerPort();
        URI serverLocation = new URI("tcp://localhost:" + port);

        for (int i = 0; i < 256; ++i) {
            transport = createTransport(serverLocation, testListener, createClientOptions());
            try {
                transport.connect(null, null);
                LOG.info("Connected to server:{} as expected.", serverLocation);
            } catch (Exception e) {
                fail("Should have connected to the server at " + serverLocation + " but got exception: " + e);
            }

            assertTrue(transport.isConnected());

            ByteBuf sendBuffer = transport.allocateSendBuffer(10 * 1024 * 1024);
            sendBuffer.writeBytes(new byte[] {0, 1, 2, 3, 4});

            transport.close();

            try {
                transport.writeAndFlush(sendBuffer);
                fail("Should throw on send of closed transport");
            } catch (IOException ex) {
            }
        }

        System.gc();
    }
}
 
Example #19
Source File: AltsTsiTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  ResourceLeakDetector.setLevel(Level.PARANOID);
  // Use MockAltsHandshakerStub for all the tests.
  AltsHandshakerOptions handshakerOptions = new AltsHandshakerOptions(null);
  MockAltsHandshakerStub clientStub = new MockAltsHandshakerStub();
  MockAltsHandshakerStub serverStub = new MockAltsHandshakerStub();
  client = new AltsHandshakerClient(clientStub, handshakerOptions);
  server = new AltsHandshakerClient(serverStub, handshakerOptions);
}
 
Example #20
Source File: InstrumentedResourceLeakDetector.java    From zuul with Apache License 2.0 5 votes vote down vote up
/**
 * This private field in the superclass needs to be reset so that we can continue reporting leaks even
 * if they're duplicates. This is ugly but ideally should not be called frequently (or at all).
 */
private void resetReportedLeaks() {
    try {
        Field reportedLeaks = ResourceLeakDetector.class.getDeclaredField("reportedLeaks");
        reportedLeaks.setAccessible(true);
        Object f = reportedLeaks.get(this);
        if (f instanceof Map) {
            ((Map) f).clear();
        }
    }
    catch (Throwable t) {
        // do nothing
    }
}
 
Example #21
Source File: LeakDetectorTestSuite.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public InternalLogger newInstance(String name) {
    InternalLogger baseLogger = ((Slf4JLoggerFactory) Slf4JLoggerFactory.INSTANCE).newInstance(name);
    if (name.equals(ResourceLeakDetector.class.getName())) {
        return new ResourceLeakAssertionLogger(baseLogger);
    } else {
        return baseLogger;
    }
}
 
Example #22
Source File: LeakDetectorSubCommand.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean handle(CommandSender sender, String[] args) {
	if (ResourceLeakDetector.isEnabled()) {
		ResourceLeakDetector.setLevel(Level.DISABLED);
		sender.sendMessage(ChatColor.YELLOW + "Disabled leak detector");
	} else {
		ResourceLeakDetector.setLevel(Level.PARANOID);
		sender.sendMessage(ChatColor.YELLOW + "Enabled leak detector");
	}
	return true;
}
 
Example #23
Source File: OutBoundBufferWaterMarkTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
protected void startSecondaryProxy() throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);
    DefaultProxyServer server = new DefaultProxyServer().setConfig(new TestProxyConfig()
            .setFrontendTcpPort(SEC_PROXY_TCP_PORT).setFrontendTlsPort(SEC_PROXY_TLS_PORT));
    prepare(server);
    server.start();
}
 
Example #24
Source File: InMemorySuiteInitializer.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({ "broker-port", "broker-ssl-port", "broker-hostname", "admin-username", "admin-password" ,
              "broker-rest-port"})
@BeforeSuite
public void beforeSuite(String port, String sslPort, String hostname, String adminUsername, String adminPassword,
        String restPort, ITestContext context)
        throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);
    LOGGER.info("Starting broker on " + port + " for suite " + context.getSuite().getName());
    StartupContext startupContext = TestUtils.initStartupContext(port, sslPort, hostname, restPort);

    BrokerConfigProvider configProvider = startupContext.getService(BrokerConfigProvider.class);
    BrokerCommonConfiguration commonConfiguration
            = configProvider.getConfigurationObject(BrokerCommonConfiguration.NAMESPACE,
                                                    BrokerCommonConfiguration.class);

    commonConfiguration.setEnableInMemoryMode(true);

    BrokerAuthConfiguration brokerAuthConfiguration
            = configProvider.getConfigurationObject(BrokerAuthConfiguration.NAMESPACE,
            BrokerAuthConfiguration.class);

    brokerAuthConfiguration.getAuthorization()
            .setEnabled(true);
    brokerAuthConfiguration.getAuthorization()
            .getDiscretionaryAccessController()
            .setClassName(MemoryDacHandler.class.getCanonicalName());
    brokerAuthConfiguration.getAuthorization()
            .getMandatoryAccessController()
            .setClassName(NoOpMacHandler.class.getCanonicalName());

    AuthManager authManager = new AuthManager(startupContext);

    authManager.start();
    restServer = new BrokerRestServer(startupContext);
    broker = new BrokerImpl(startupContext);
    broker.startMessageDelivery();
    server = new Server(startupContext);
    server.start();
    restServer.start();
}
 
Example #25
Source File: NetworkBuilder.java    From asteria-3.0 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initializes this network handler effectively preparing the server to
 * listen for connections and handle network events.
 *
 * @param port
 *            the port that this network will be bound to.
 * @throws Exception
 *             if any issues occur while starting the network.
 */
public void initialize(int port) throws IOException {
    if (port != 43594 && port != 5555 && port != 43595)
        logger.warning("The preferred ports for Runescape servers are 43594, 5555, and 43595!");
    ResourceLeakDetector.setLevel(Server.DEBUG ? Level.PARANOID : NetworkConstants.RESOURCE_DETECTION);
    bootstrap.group(loopGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(channelInitializer);
    bootstrap.bind(port).syncUninterruptibly();
}
 
Example #26
Source File: MainClassUtils.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up the Netty leak detection level to one of the {@link ResourceLeakDetector.Level} options. Honors the
 * {@link #NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY} System property if available first (which matches the private
 * constant {@link ResourceLeakDetector#PROP_LEVEL} which Netty uses). If that System property is not set then the
 * given argument will be used to extract the relevant level value from the application properties and use that if
 * it's not null. NOTE: The logic for pulling from the application properties is as follows:
 * <pre>
 * <ol>
 *     <li>
 *         The system property key will be checked in the application properties first:
 *         {@link #NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY}
 *     </li>
 *     <li>
 *         If the system property key is not found in the application properties, then a slightly different key that
 *         is nicer for application properties files will be checked:
 *         {@link #NETTY_LEAK_DETECTION_LEVEL_APP_PROP_KEY}
 *     </li>
 * </ol>
 * </pre>
 * If the level is not specified in either System or application properties then this method will do nothing,
 * leaving the Netty default to be used.
 *
 * @param hasPropertyFunction
 *     A function that returns true if the argument to the function is a property key that exists.
 * @param propertyExtractionFunction
 *     A function that accepts a property key as an argument and returns the property value as a string. The {@code
 *     hasPropertyFunction} arg will be used to guarantee the property exists before this function is called.
 */
public static void setupNettyLeakDetectionLevel(
    @NotNull Function<String, Boolean> hasPropertyFunction,
    @NotNull Function<String, String> propertyExtractionFunction
) {
    String nettyLeakDetectionLevel = System.getProperty(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY);
    if (nettyLeakDetectionLevel == null) {
        // No system property. See if it's specified in the app properties.
        if (hasPropertyFunction.apply(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY)) {
            nettyLeakDetectionLevel = propertyExtractionFunction.apply(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY);
        }
        else if (hasPropertyFunction.apply(NETTY_LEAK_DETECTION_LEVEL_APP_PROP_KEY)) {
            nettyLeakDetectionLevel = propertyExtractionFunction.apply(NETTY_LEAK_DETECTION_LEVEL_APP_PROP_KEY);
        }
    }

    if (nettyLeakDetectionLevel == null) {
        logger.info("No netty leak detection level specified in System or application properties. "
                    + "The default Netty behavior will be used. netty_leak_detection_level_used={}",
                    ResourceLeakDetector.getLevel()
        );
    }
    else {
        nettyLeakDetectionLevel = nettyLeakDetectionLevel.toUpperCase();
        logger.info("Netty leak detection level specified in the System properties or application properties. "
                    + "netty_leak_detection_level_used={}",
                    nettyLeakDetectionLevel
        );
        System.setProperty(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY, nettyLeakDetectionLevel);
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(nettyLeakDetectionLevel));
    }
}
 
Example #27
Source File: DisplayLeaksSubCmd.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public boolean execute(ViaCommandSender sender, String[] args) {
    if (ResourceLeakDetector.getLevel() != ResourceLeakDetector.Level.ADVANCED)
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    else
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);

    sendMessage(sender, "&6Leak detector is now %s", (ResourceLeakDetector.getLevel() == ResourceLeakDetector.Level.ADVANCED ? "&aenabled" : "&cdisabled"));
    return true;
}
 
Example #28
Source File: Client.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
public Client() {
	ResourceLeakDetector.setLevel(Level.DISABLED);

	client = new TurboClient("turbo-client.conf");

	try {
		client.register(TurboUserService.class);
		userService = client.getService(TurboUserService.class);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #29
Source File: Server.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	ResourceLeakDetector.setLevel(Level.DISABLED);

	try (TurboServer server = new TurboServer("shop", "auth");) {
		Map<Class<?>, Object> services = Map.of(TurboUserService.class, new TurboUserServiceServerImpl());
		server.registerService(services);

		server.startRestServer(new HostPort("benchmark-server", 8080));
		server.waitUntilShutdown();
	}
}
 
Example #30
Source File: StyxServerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void disablesResourceLeakDetectionByDefault() {
    StyxServerComponents config = new StyxServerComponents.Builder()
            .configuration(EMPTY_CONFIGURATION)
            .additionalServices(ImmutableMap.of("backendServiceRegistry", new RegistryServiceAdapter(new MemoryBackedRegistry<>())))
            .build();

    new StyxServer(config);

    assertThat(ResourceLeakDetector.getLevel(), is(DISABLED));
}