Java Code Examples for io.netty.util.ResourceLeakDetector#setLevel()

The following examples show how to use io.netty.util.ResourceLeakDetector#setLevel() . 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: 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 2
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 3
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 4
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 5
Source File: AltsTsiTest.java    From grpc-nebula-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 6
Source File: KeplerWeb.java    From Kepler with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    WebLoggingConfiguration.checkLoggingConfig();

    ServerConfiguration.setWriter(new WebServerConfigWriter());
    ServerConfiguration.load("webserver-config.ini");

    logger.info("HavanaWeb by Quackster");
    logger.info("Loading configuration..");

    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);

    Settings settings = Settings.getInstance();
    settings.setSiteDirectory(ServerConfiguration.getString("site.directory"));
    settings.setDefaultResponses(new ServerResponses());
    settings.setTemplateBase(TwigTemplate.class);

    if (!Storage.connect()) {
        Log.getErrorLogger().error("Could not connect to MySQL");
        return;
    }

    GameConfiguration.getInstance(new WebSettingsConfigWriter());

    scheduler = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
    scheduler.scheduleWithFixedDelay(new Watchdog(), 1, 1, TimeUnit.SECONDS);

    logger.info("Registering web routes..");
    Routes.register();
    logger.info("Registered " + RouteManager.getRoutes().size() + " route(s)!");

    int port = ServerConfiguration.getInteger("bind.port");
    logger.info("Starting http service on port " + port);

    setupTemplateSystem();
    WebServer instance = new WebServer(port);
    instance.start();
}
 
Example 7
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 8
Source File: LeakDetectSubCommand.java    From ViaFabric with MIT License 5 votes vote down vote up
@Override
public boolean execute(ViaCommandSender viaCommandSender, String[] strings) {
    if (strings.length == 1) {
        try {
            ResourceLeakDetector.Level level = ResourceLeakDetector.Level.valueOf(strings[0]);
            ResourceLeakDetector.setLevel(level);
            viaCommandSender.sendMessage("Set leak detector level to " + level);
        } catch (IllegalArgumentException e) {
            viaCommandSender.sendMessage("Invalid level (" + Arrays.toString(ResourceLeakDetector.Level.values()) + ")");
        }
    } else {
        viaCommandSender.sendMessage("Current leak detection level is " + ResourceLeakDetector.getLevel());
    }
    return true;
}
 
Example 9
Source File: DefaultSuiteInitializer.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);
    BrokerAuthConfiguration brokerAuthConfiguration
            = configProvider.getConfigurationObject(BrokerAuthConfiguration.NAMESPACE,
                                                    BrokerAuthConfiguration.class);

    brokerAuthConfiguration.getAuthorization()
                           .setEnabled(true);
    brokerAuthConfiguration.getAuthorization()
                           .getDiscretionaryAccessController()
                           .setClassName(RdbmsDacHandler.class.getCanonicalName());
    brokerAuthConfiguration.getAuthorization()
                           .getMandatoryAccessController()
                           .setClassName(DefaultMacHandler.class.getCanonicalName());

    DbUtils.setupDB();
    DataSource dataSource = DbUtils.getDataSource();
    startupContext.registerService(DataSource.class, dataSource);

    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 10
Source File: LunaServer.java    From luna with MIT License 5 votes vote down vote up
/**
 * Initializes the network server using Netty.
 */
private void initNetwork() {

    ResourceLeakDetector.setLevel(Luna.settings().resourceLeakDetection());

    ServerBootstrap bootstrap = new ServerBootstrap();
    EventLoopGroup loopGroup = new NioEventLoopGroup();

    bootstrap.group(loopGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new LunaChannelInitializer(context, channelFilter, messageRepository));
    bootstrap.bind(Luna.settings().port()).syncUninterruptibly();
}
 
Example 11
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 12
Source File: HttpDownSpringBoot.java    From proxyee-down with Apache License 2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
  if ("dev".equalsIgnoreCase(active.trim())) {
    ResourceLeakDetector.setLevel(Level.ADVANCED);
  }
}
 
Example 13
Source File: NettyServer.java    From blade with Apache License 2.0 4 votes vote down vote up
private void startServer(long startMs) throws Exception {

        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);

        boolean SSL = environment.getBoolean(ENV_KEY_SSL, false);
        // Configure SSL.
        SslContext sslCtx = null;
        if (SSL) {
            String certFilePath       = environment.get(ENV_KEY_SSL_CERT, null);
            String privateKeyPath     = environment.get(ENE_KEY_SSL_PRIVATE_KEY, null);
            String privateKeyPassword = environment.get(ENE_KEY_SSL_PRIVATE_KEY_PASS, null);

            log.info("{}SSL CertChainFile  Path: {}", getStartedSymbol(), certFilePath);
            log.info("{}SSL PrivateKeyFile Path: {}", getStartedSymbol(), privateKeyPath);
            sslCtx = SslContextBuilder.forServer(new File(certFilePath), new File(privateKeyPath), privateKeyPassword).build();
        }

        var bootstrap = new ServerBootstrap();

        int acceptThreadCount = environment.getInt(ENC_KEY_NETTY_ACCEPT_THREAD_COUNT, DEFAULT_ACCEPT_THREAD_COUNT);
        int ioThreadCount     = environment.getInt(ENV_KEY_NETTY_IO_THREAD_COUNT, DEFAULT_IO_THREAD_COUNT);

        // enable epoll
        if (BladeKit.epollIsAvailable()) {
            log.info("{}Use EpollEventLoopGroup", getStartedSymbol());
            bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);

            NettyServerGroup nettyServerGroup = EpollKit.group(acceptThreadCount, ioThreadCount);
            this.bossGroup = nettyServerGroup.getBoosGroup();
            this.workerGroup = nettyServerGroup.getWorkerGroup();
            bootstrap.group(bossGroup, workerGroup).channel(nettyServerGroup.getSocketChannel());
        } else {
            log.info("{}Use NioEventLoopGroup", getStartedSymbol());

            this.bossGroup = new NioEventLoopGroup(acceptThreadCount, new NamedThreadFactory("boss@"));
            this.workerGroup = new NioEventLoopGroup(ioThreadCount, new NamedThreadFactory("worker@"));
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
        }

        scheduleEventLoop = new DefaultEventLoop();

        bootstrap.childHandler(new HttpServerInitializer(sslCtx, blade, scheduleEventLoop));

        String  address = environment.get(ENV_KEY_SERVER_ADDRESS, DEFAULT_SERVER_ADDRESS);
        Integer port    = environment.getInt(ENV_KEY_SERVER_PORT, DEFAULT_SERVER_PORT);

        channel = bootstrap.bind(address, port).sync().channel();

        String appName  = environment.get(ENV_KEY_APP_NAME, "Blade");
        String url      = Ansi.BgRed.and(Ansi.Black).format(" %s:%d ", address, port);
        String protocol = SSL ? "https" : "http";

        log.info("{}{} initialize successfully, Time elapsed: {} ms", getStartedSymbol(), appName, (System.currentTimeMillis() - startMs));
        log.info("{}Blade start with {}", getStartedSymbol(), url);
        log.info("{}Open browser access {}://{}:{} ⚡\r\n", getStartedSymbol(), protocol, address.replace(DEFAULT_SERVER_ADDRESS, LOCAL_IP_ADDRESS), port);

        blade.eventManager().fireEvent(EventType.SERVER_STARTED, new Event().attribute("blade", blade));
    }
 
Example 14
Source File: AbstractTest.java    From x-pipe with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeAbstractTest() throws Exception {

    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);
    Thread.interrupted();//clear interrupt

    executors = Executors.newCachedThreadPool(XpipeThreadFactory.create(getTestName()));
    scheduled = Executors.newScheduledThreadPool(OsUtils.getCpuCount(), XpipeThreadFactory.create(getTestName()));

    orginProperties = (Properties) System.getProperties().clone();

    doBeforeAbstractTest();


    logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName());

    componentRegistry = new DefaultRegistry(new CreatedComponentRedistry(), getSpringRegistry());

    startedComponentRegistry = new CreatedComponentRedistry();
    startedComponentRegistry.initialize();
    startedComponentRegistry.start();

    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
    InputStream fins = getClass().getClassLoader().getResourceAsStream("xpipe-test.properties");
    try {
        properties.load(fins);
    } finally {
        if (fins != null) {
            fins.close();
        }
    }

    File file = new File(getTestFileDir());
    if (file.exists() && deleteTestDirBeforeTest()) {
        deleteTestDir();
    }

    if (!file.exists()) {
        boolean testSucceed = file.mkdirs();
        if (!testSucceed) {
            throw new IllegalStateException("test dir make failed!" + file);
        }
    }
}
 
Example 15
Source File: EpollReuseAddrTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 10000)
@Ignore // TODO: Unignore after making it pass on centos6-1 and debian7-1
public void testMultipleBindDatagramChannel() throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
    Assume.assumeTrue(versionEqOrGt(3, 9, 0));
    Bootstrap bootstrap = createBootstrap();
    bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
    final AtomicBoolean received1 = new AtomicBoolean();
    bootstrap.handler(new DatagramSocketTestHandler(received1));
    ChannelFuture future = bootstrap.bind().syncUninterruptibly();
    final InetSocketAddress address1 = (InetSocketAddress) future.channel().localAddress();

    final AtomicBoolean received2 = new AtomicBoolean();
    bootstrap.handler(new DatagramSocketTestHandler(received2));
    ChannelFuture future2 = bootstrap.bind(address1).syncUninterruptibly();
    final InetSocketAddress address2 = (InetSocketAddress) future2.channel().localAddress();

    Assert.assertEquals(address1, address2);
    final byte[] bytes = "data".getBytes();

    // fire up 16 Threads and send DatagramPackets to make sure we stress it enough to see DatagramPackets received
    // on both sockets.
    int count = 16;
    final CountDownLatch latch = new CountDownLatch(count);
    Runnable r = new Runnable() {
        @Override
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket();
                while (!received1.get() || !received2.get()) {
                    socket.send(new DatagramPacket(
                            bytes, 0, bytes.length, address1.getAddress(), address1.getPort()));
                }
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            latch.countDown();
        }
    };

    ExecutorService executor = Executors.newFixedThreadPool(count);
    for (int i = 0 ; i < count; i++) {
        executor.execute(r);
    }
    latch.await();
    executor.shutdown();
    future.channel().close().syncUninterruptibly();
    future2.channel().close().syncUninterruptibly();
    Assert.assertTrue(received1.get());
    Assert.assertTrue(received2.get());
}
 
Example 16
Source File: ResourceLeakDetectorRecordBenchmark.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@TearDown(Level.Trial)
public void teardown() {
    ResourceLeakDetector.setLevel(level);
}
 
Example 17
Source File: ResourceLeakDetectorRecordBenchmark.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Setup(Level.Trial)
public void setup() {
    level = ResourceLeakDetector.getLevel();
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);
}
 
Example 18
Source File: LeakDetectorTestSuite.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Override
@After
public void after() throws InterruptedException {
    super.after();
    ResourceLeakDetector.setLevel(this.originalLevel);
}
 
Example 19
Source File: AltsChannelCrypterTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws GeneralSecurityException {
  ResourceLeakDetector.setLevel(Level.PARANOID);
  client = new AltsChannelCrypter(new byte[AltsChannelCrypter.getKeyLength()], true);
  server = new AltsChannelCrypter(new byte[AltsChannelCrypter.getKeyLength()], false);
}
 
Example 20
Source File: AltsTsiFrameProtectorTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  ResourceLeakDetector.setLevel(Level.PARANOID);
}