@Test public void testExecuteMultiThreadRpc() { Random rand = new Random(System.currentTimeMillis()); ResourceLeakDetector.setLevel(Level.PARANOID); GridConfiguration config = GridConfigFactory.configure(this.getClass().getResourceAsStream("/grid-config.xml")); GridRuntime.initialize(config); RpcExecutor.registerMethod("print", RemoteObject.class, new RemoteObject()); RpcExecutor.registerMethod("add", RemoteObject.class, new RemoteObject()); ThreadUtils.threadSleep(5000); for (int i = 1; i <= 100; i++) { int a = rand.nextInt(100); int b = rand.nextInt(100); long st = System.currentTimeMillis(); RpcResult result = RpcExecutor.callMethod("add", new Object[]{a, b}, new ExecuteConfig()); System.out.println("==========>" + i + " " + result + " cost:" + (System.currentTimeMillis() - st)); ThreadUtils.threadSleep(10); } while(true) { ThreadUtils.threadSleep(10000); } }
@Override public void afterPropertiesSet() throws Exception { ACTIVE = active; if (isDev()) { VIEW_SERVER_PORT = viewServerPort; ResourceLeakDetector.setLevel(Level.ADVANCED); } else { VIEW_SERVER_PORT = OsUtil.getFreePort(); } }
/** * Builds the network by creating the netty server bootstrap and binding to a specified port. * * @return The instance of this bootstrap. */ public Bootstrap bind() throws InterruptedException { logger.info("Building network"); ResourceLeakDetector.setLevel(Level.DISABLED); EventLoopGroup loopGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(loopGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelPiplineInitializer()).bind(43593 + world.getId()).syncUninterruptibly(); Server.serverStarted = true; logger.info(String.format("World %d has been bound to port %d", world.getId(), world.getPort())); return this; }
@Before public void setup() throws Exception { originalLevel = ResourceLeakDetector.getLevel(); ResourceLeakDetector.setLevel(Level.PARANOID); InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE); this.serviceBuilder = ServiceBuilder.newInMemoryBuilder(ServiceBuilderConfig.getDefaultConfig()); this.serviceBuilder.initialize(); }
/** * 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(); }
@Test public void testStartup() { ResourceLeakDetector.setLevel(Level.PARANOID); GridConfiguration config = GridConfigFactory.configure(this.getClass().getResourceAsStream("/grid-config.xml")); GridRuntime.initialize(config); while(true) { ThreadUtils.threadSleep(10000); } }
@Test public void testStartRpcNode() { ResourceLeakDetector.setLevel(Level.PARANOID); GridConfiguration config = GridConfigFactory.configure(this.getClass().getResourceAsStream("/grid-config.xml")); GridRuntime.initialize(config); RpcExecutor.registerMethod("print", RemoteObject.class, new RemoteObject()); RpcExecutor.registerMethod("add", RemoteObject.class, new RemoteObject()); while(true) { ThreadUtils.threadSleep(10000); } }
@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; }
@Test public void testAsyncSocketServer() throws Exception { ResourceLeakDetector.setLevel(Level.ADVANCED); TransientMockNetworkOfNodes mockNetworkOfNodes=new TransientMockNetworkOfNodes(); final CountDownLatch serverDoneBarrier = new CountDownLatch(NB_CLIENTS*NUMBER_OF_MESSAGE); MessageEchoApp serverSideCountingHandler=new MessageEchoApp(mockNetworkOfNodes.server1, serverDoneBarrier); final CountDownLatch clientsDoneBarrier = new CountDownLatch(NB_CLIENTS); for(int i=0; i<NB_CLIENTS; i++){ new Thread(){ @Override public void run() { try { doNettyClientWrite(mockNetworkOfNodes.client1ToServer1Connection); clientsDoneBarrier.countDown(); } catch (Exception e) { e.printStackTrace(); } } }.start(); } clientsDoneBarrier.await(); mockNetworkOfNodes.client1ToServer1Connection.close(); serverDoneBarrier.await(); mockNetworkOfNodes.server1.networkServer.stopAcceptingConnections(); assertEquals(NB_CLIENTS*NUMBER_OF_MESSAGE, serverSideCountingHandler.numberOfMessagesReceived.intValue()); }
@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); 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.send(sendBuffer); fail("Should throw on send of closed transport"); } catch (IOException ex) { } } System.gc(); } }
private void resetNettyLeakDetectionLevel() { System.clearProperty(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY); ResourceLeakDetector.setLevel(Level.SIMPLE); }
@DataProvider(value = { // no-op case "null | null | null | null", // cases showing that system property takes precedence over everything "PARANOID | null | null | PARANOID", "disabled | PARANOID | null | DISABLED", // also - lowercase works "aDvAnCeD | PARANOID | DISABLED | ADVANCED", // also - mixed case works // cases showing that NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY takes precedence // over NETTY_LEAK_DETECTION_LEVEL_APP_PROP_KEY if the system property is absent "null | ADVANCED | null | ADVANCED", "null | aDvAnCeD | PARANOID | ADVANCED", // yes, lower/mixed case still works here too // cases showing NETTY_LEAK_DETECTION_LEVEL_APP_PROP_KEY will be used if the other // options are not available "null | null | DISABLED | DISABLED", "null | null | pArAnOiD | PARANOID", // yes, lower/mixed case still works here too }, splitBy = "\\|") @Test public void setupNettyLeakDetectionLevel_works_as_expected( String systemPropValue, String configValueForSystemPropKey, String configValueForAppPropKey, Level expectedFinalLevel ) { // given assertThat(ResourceLeakDetector.getLevel()).isEqualTo(Level.SIMPLE); assertThat(expectedFinalLevel).isNotEqualTo(Level.SIMPLE); setSystemPropWithNullSupport(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY, systemPropValue); Function<String, String> propertyExtractionFunction = (key) -> { switch(key) { case NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY: return configValueForSystemPropKey; case NETTY_LEAK_DETECTION_LEVEL_APP_PROP_KEY: return configValueForAppPropKey; default: throw new IllegalArgumentException("Unhandled config key: " + key); } }; Function<String, Boolean> hasPropertyFunction = (key) -> (propertyExtractionFunction.apply(key) != null); // when MainClassUtils.setupNettyLeakDetectionLevel(hasPropertyFunction, propertyExtractionFunction); // then if (expectedFinalLevel == null) { // We expect that the method did nothing since it couldn't find anything to set assertThat(System.getProperty(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY)).isNull(); assertThat(ResourceLeakDetector.getLevel()).isEqualTo(Level.SIMPLE); } else { assertThat(System.getProperty(NETTY_LEAK_DETECTION_LEVEL_SYSTEM_PROP_KEY)) .isEqualTo(expectedFinalLevel.name()); assertThat(ResourceLeakDetector.getLevel()).isEqualTo(expectedFinalLevel); } }
@Test public void testByteBufsReleasedWhenTimeout() { ResourceLeakDetector.setLevel(Level.PARANOID); byte[] content = new byte[1024*8]; Random rndm = new Random(); rndm.nextBytes(content); NettyContext server1 = HttpServer.create(0) .newRouter(routes -> routes.get("/target", (req, res) -> res.sendByteArray(Flux.just(content) .delayElements(Duration.ofMillis(100))))) .block(Duration.ofSeconds(30)); NettyContext server2 = HttpServer.create(0) .newRouter(routes -> routes.get("/forward", (req, res) -> HttpClient.create(server1.address().getPort()) .get("/target") .log() .delayElement(Duration.ofMillis(50)) .flatMap(response -> response.receive().aggregate().asString()) .timeout(Duration.ofMillis(50)) .then())) .block(Duration.ofSeconds(30)); Flux.range(0, 50) .flatMap(i -> HttpClient.create(server2.address().getPort()) .get("/forward") .log() .onErrorResume(t -> Mono.empty())) .blockLast(Duration.ofSeconds(30)); server1.dispose(); server2.dispose(); ResourceLeakDetector.setLevel(Level.SIMPLE); }
@Override public void initChannel(SocketChannel ch) throws Exception { IConfig cfg = Config.getInstance(); //if we need to check for ByteBuf leaks. if(cfg.isLeakDetector()){ ResourceLeakDetector.setLevel(Level.ADVANCED); } //so we get enough data to build our pipeline ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(1024)); ChannelPipeline pipeline = ch.pipeline(); int incomingPort = ch.localAddress().getPort(); //if users are coming in on a different port than the proxy port we need to redirect them. if(cfg.isProxy() && cfg.getPort() != incomingPort){ redirectBuilder.apply(pipeline); return; } if (cfg.isEncrypted()) { SslContext sslContext = factory.createSslContext(Config.getInstance()); SSLEngine engine = sslContext.newEngine(ch.alloc()); engine.setUseClientMode(false); engine.setNeedClientAuth(cfg.isCertAuth()); ch.pipeline().addFirst("ssl",new SslHandler(engine)); } if(cfg.isProxy()){ pipeline.channel().config().setAutoRead(false); pipeline.addLast(guicer.inject(new ProxyFrontendHandler(cfg.getProxyBackendHost(),cfg.getProxyBackendPort()))); }else{ websocketBuilder.apply(pipeline); } }
@Before public void setup() { origionalLogLevel = ResourceLeakDetector.getLevel(); ResourceLeakDetector.setLevel(Level.PARANOID); }
@Before public void setUp() throws Exception { ResourceLeakDetector.setLevel(Level.ADVANCED); DefaultCredentials conf = getConf(); apns = new DefaultApnsConnection(conf); }
/** * Called from Hub.start this method configures the logging features. * * @param config xml holding the configuration */ static public void init(XElement config) { HubLog.config = config; // TODO return operation result // TODO load levels, path etc // include a setting for startup logging - if present set the TC log level directly HubLog.startNewLogFile(); // set by operation context init //Logger.locale = LocaleUtil.getDefaultLocale(); // From here on we can use netty and so we need the logger setup InternalLoggerFactory.setDefaultFactory(new divconq.log.netty.LoggerFactory()); if (HubLog.config != null) { // set by operation context init //if (Logger.config.hasAttribute("Level")) // Logger.globalLevel = DebugLevel.parse(Logger.config.getAttribute("Level")); if (HubLog.config.hasAttribute("Level")) HubLog.setGlobalLevel(DebugLevel.parse(HubLog.config.getAttribute("Level"))); if (HubLog.config.hasAttribute("EnableDebugger")) HubLog.debugEnabled = "True".equals(HubLog.config.getAttribute("EnableDebugger")); if (HubLog.config.hasAttribute("NettyLevel")) { ResourceLeakDetector.setLevel(Level.valueOf(HubLog.config.getAttribute("NettyLevel"))); Logger.debug("Netty Level set to: " + ResourceLeakDetector.getLevel()); } else if (!"none".equals(System.getenv("dcnet"))) { // TODO anything more we should do here? maybe paranoid isn't helpful? } // set by operation context init //if (Logger.config.hasAttribute("Locale")) // Logger.locale = Logger.config.getAttribute("Locale"); } }