use of io.netty.channel.group.DefaultChannelGroup in project resteasy by resteasy.
the class ReactorTest method testTimeoutOverridePerRequest.
@Test
public void testTimeoutOverridePerRequest() throws Exception {
// This also tests that the client will eagerly close the connection
// in the case of a business logic timeout.
final Duration serverResponseDelay = Duration.ofSeconds(60);
final CountDownLatch serverConnDisconnectingEvent = new CountDownLatch(1);
final DisposableServer server = HttpServer.create().childObserve((conn, state) -> {
if (state == ConnectionObserver.State.DISCONNECTING) {
serverConnDisconnectingEvent.countDown();
}
}).handle((req, resp) -> resp.sendString(Mono.just("I'm delayed!").delayElement(serverResponseDelay))).bindNow();
try {
final CountDownLatch latch = new CountDownLatch(1);
final HttpClient reactorClient = HttpClient.create();
final ReactorNettyClientHttpEngine reactorEngine = new ReactorNettyClientHttpEngine(reactorClient, new DefaultChannelGroup(new DefaultEventExecutor()), ConnectionProvider.builder("clientconns").maxConnections(1).build());
final AtomicReference<Exception> innerTimeoutException = new AtomicReference<>();
final ReactiveClientHttpEngine wrappedEngine = new ReactiveClientHttpEngine() {
private <T> Mono<T> recordTimeout(final Mono<T> m) {
return m.doOnError(TimeoutException.class, innerTimeoutException::set);
}
public <T> Mono<T> submitRx(ClientInvocation request, boolean buffered, ResultExtractor<T> extractor) {
return recordTimeout(reactorEngine.submitRx(request, buffered, extractor));
}
public <T> Mono<T> fromCompletionStage(CompletionStage<T> cs) {
return recordTimeout(reactorEngine.fromCompletionStage(cs));
}
public <T> Mono<T> just(T t) {
return recordTimeout(reactorEngine.just(t));
}
public Mono error(Exception e) {
return recordTimeout(reactorEngine.error(e));
}
public <T> Future<T> submit(ClientInvocation request, boolean buffered, InvocationCallback<T> callback, ResultExtractor<T> extractor) {
return reactorEngine.submit(request, buffered, callback, extractor);
}
public <K> CompletableFuture<K> submit(ClientInvocation request, boolean buffered, ResultExtractor<K> extractor, ExecutorService executorService) {
return reactorEngine.submit(request, buffered, extractor, executorService);
}
public SSLContext getSslContext() {
return reactorEngine.getSslContext();
}
public HostnameVerifier getHostnameVerifier() {
return reactorEngine.getHostnameVerifier();
}
public Response invoke(Invocation request) {
return reactorEngine.invoke(request);
}
public void close() {
reactorEngine.close();
}
};
final Duration innerTimeout = Duration.ofSeconds(5);
final ResteasyClient client = ((ResteasyClientBuilder) ClientBuilder.newBuilder()).httpEngine(wrappedEngine).readTimeout(innerTimeout.toMillis(), TimeUnit.MILLISECONDS).build();
client.target("http://localhost:" + server.port() + "/").request().rx(MonoRxInvoker.class).get(String.class).timeout(Duration.ofMillis(500)).subscribe(ignore -> {
fail("Should have got timeout exception");
}, t -> {
if (!(t instanceof TimeoutException)) {
// crappy assertion:(
assertThat(t.getMessage(), containsString("signal within 500ms"));
}
latch.countDown();
}, latch::countDown);
assertNull("Inner timeout should not have occurred!", innerTimeoutException.get());
assertTrue("Test timed out", latch.await(innerTimeout.multipliedBy(2).toMillis(), TimeUnit.MILLISECONDS));
assertTrue("Server disconnect didn't happen.", serverConnDisconnectingEvent.await(serverResponseDelay.dividedBy(2).toMillis(), TimeUnit.MILLISECONDS));
} finally {
server.disposeNow();
}
}
use of io.netty.channel.group.DefaultChannelGroup in project resteasy by resteasy.
the class ReactorTest method testSubscriberContext.
@Test
public void testSubscriberContext() {
final String ctxKey = "secret";
final List<Integer> secrets = new ArrayList<>();
// With the `Publisher` bridge, the end user's subscriber context is available when the
// reactor-netty client is instantiated. This can be useful for things like trace logging.
final HttpClient reactorClient = HttpClient.create().doOnRequest((req, conn) -> req.currentContext().<Integer>getOrEmpty(ctxKey).ifPresent(secrets::add));
final ReactorNettyClientHttpEngine reactorEngine = new ReactorNettyClientHttpEngine(reactorClient, new DefaultChannelGroup(new DefaultEventExecutor()), ConnectionProvider.newConnection());
final ResteasyClient client = ((ResteasyClientBuilder) ClientBuilder.newBuilder()).httpEngine(reactorEngine).readTimeout(5, TimeUnit.SECONDS).connectionCheckoutTimeout(5, TimeUnit.SECONDS).connectTimeout(5, TimeUnit.SECONDS).build();
final Supplier<Mono<String>> getFn = () -> client.target(generateURL("/mono")).request().rx(MonoRxInvoker.class).get(String.class);
Mono<String> mono = getFn.get().flatMap(resp1 -> getFn.get().flatMap(resp2 -> getFn.get().map(resp3 -> String.join("-", Arrays.asList(resp1, resp2, resp3))).subscriberContext(Context.of(ctxKey, 24)))).subscriberContext(ctx -> ctx.put(ctxKey, 42));
assertThat(mono.block(), equalTo("got it-got it-got it"));
assertThat(secrets, equalTo(Arrays.asList(42, 42, 24)));
}
use of io.netty.channel.group.DefaultChannelGroup in project activemq-artemis by rh-messaging.
the class NettyAcceptor method start.
@Override
public synchronized void start() throws Exception {
if (channelClazz != null) {
// Already started
return;
}
String acceptorType;
if (useInvm) {
acceptorType = INVM_ACCEPTOR_TYPE;
channelClazz = LocalServerChannel.class;
eventLoopGroup = new DefaultEventLoopGroup();
} else {
if (remotingThreads == -1) {
// Default to number of cores * 3
remotingThreads = Runtime.getRuntime().availableProcessors() * 3;
}
if (useEpoll && CheckDependencies.isEpollAvailable()) {
channelClazz = EpollServerSocketChannel.class;
eventLoopGroup = new EpollEventLoopGroup(remotingThreads, AccessController.doPrivileged(new PrivilegedAction<ActiveMQThreadFactory>() {
@Override
public ActiveMQThreadFactory run() {
return new ActiveMQThreadFactory("activemq-netty-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
}
}));
acceptorType = EPOLL_ACCEPTOR_TYPE;
logger.debug("Acceptor using native epoll");
} else if (useKQueue && CheckDependencies.isKQueueAvailable()) {
channelClazz = KQueueServerSocketChannel.class;
eventLoopGroup = new KQueueEventLoopGroup(remotingThreads, AccessController.doPrivileged(new PrivilegedAction<ActiveMQThreadFactory>() {
@Override
public ActiveMQThreadFactory run() {
return new ActiveMQThreadFactory("activemq-netty-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
}
}));
acceptorType = KQUEUE_ACCEPTOR_TYPE;
logger.debug("Acceptor using native kqueue");
} else {
channelClazz = NioServerSocketChannel.class;
eventLoopGroup = new NioEventLoopGroup(remotingThreads, AccessController.doPrivileged(new PrivilegedAction<ActiveMQThreadFactory>() {
@Override
public ActiveMQThreadFactory run() {
return new ActiveMQThreadFactory("activemq-netty-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
}
}));
acceptorType = NIO_ACCEPTOR_TYPE;
logger.debug("Acceptor using nio");
}
}
bootstrap = new ServerBootstrap();
bootstrap.group(eventLoopGroup);
bootstrap.channel(channelClazz);
ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
Pair<String, Integer> peerInfo = getPeerInfo(channel);
if (sslEnabled) {
try {
pipeline.addLast("ssl", getSslHandler(channel.alloc(), peerInfo.getA(), peerInfo.getB()));
pipeline.addLast("sslHandshakeExceptionHandler", new SslHandshakeExceptionHandler());
} catch (Exception e) {
Throwable rootCause = getRootCause(e);
ActiveMQServerLogger.LOGGER.gettingSslHandlerFailed(channel.remoteAddress().toString(), rootCause.getClass().getName() + ": " + rootCause.getMessage());
if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
ActiveMQServerLogger.LOGGER.debug("Getting SSL handler failed", e);
}
throw e;
}
}
pipeline.addLast(protocolHandler.getProtocolDecoder());
}
private Pair<String, Integer> getPeerInfo(Channel channel) {
try {
String[] peerInfo = channel.remoteAddress().toString().replace("/", "").split(":");
return new Pair<>(peerInfo[0], Integer.parseInt(peerInfo[1]));
} catch (Exception e) {
logger.debug("Failed to parse peer info for SSL engine initialization", e);
}
return new Pair<>(null, 0);
}
};
bootstrap.childHandler(factory);
// Bind
bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
if (tcpReceiveBufferSize != -1) {
bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
}
if (tcpSendBufferSize != -1) {
bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
}
final int writeBufferLowWaterMark = this.writeBufferLowWaterMark != -1 ? this.writeBufferLowWaterMark : WriteBufferWaterMark.DEFAULT.low();
final int writeBufferHighWaterMark = this.writeBufferHighWaterMark != -1 ? this.writeBufferHighWaterMark : WriteBufferWaterMark.DEFAULT.high();
final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(writeBufferLowWaterMark, writeBufferHighWaterMark);
bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);
if (backlog != -1) {
bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
}
bootstrap.option(ChannelOption.SO_REUSEADDR, true);
bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);
serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);
if (httpUpgradeEnabled) {
// the channel will be bound by the Web container and hand over after the HTTP Upgrade
// handshake is successful
} else {
startServerChannels();
paused = false;
if (notificationService != null) {
TypedProperties props = new TypedProperties();
props.putSimpleStringProperty(new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName()));
props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
props.putIntProperty(new SimpleString("port"), port);
Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
notificationService.sendNotification(notification);
}
ActiveMQServerLogger.LOGGER.startedAcceptor(acceptorType, host, port, protocolsString);
}
if (batchDelay > 0) {
flusher = new BatchFlusher();
batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS);
}
}
use of io.netty.channel.group.DefaultChannelGroup in project zuul by Netflix.
the class BaseZuulChannelInitializerTest method serverStateHandlerAdded.
@Test
public void serverStateHandlerAdded() {
ChannelConfig channelConfig = new ChannelConfig();
ChannelConfig channelDependencies = new ChannelConfig();
channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry());
channelDependencies.set(ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
channelDependencies.set(ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());
ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
BaseZuulChannelInitializer init = new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) {
@Override
protected void initChannel(Channel ch) {
}
};
EmbeddedChannel channel = new EmbeddedChannel();
init.addPassportHandler(channel.pipeline());
assertNotNull(channel.pipeline().context(ServerStateHandler.InboundHandler.class));
assertNotNull(channel.pipeline().context(ServerStateHandler.OutboundHandler.class));
}
use of io.netty.channel.group.DefaultChannelGroup in project zuul by Netflix.
the class BaseZuulChannelInitializerTest method tcpHandlersAdded.
@Test
public void tcpHandlersAdded() {
ChannelConfig channelConfig = new ChannelConfig();
ChannelConfig channelDependencies = new ChannelConfig();
channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry());
channelDependencies.set(ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
channelDependencies.set(ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());
ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
BaseZuulChannelInitializer init = new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) {
@Override
protected void initChannel(Channel ch) {
}
};
EmbeddedChannel channel = new EmbeddedChannel();
init.addTcpRelatedHandlers(channel.pipeline());
assertNotNull(channel.pipeline().context(SourceAddressChannelHandler.class));
assertNotNull(channel.pipeline().context(PerEventLoopMetricsChannelHandler.Connections.class));
assertNotNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME));
assertNotNull(channel.pipeline().context(MaxInboundConnectionsHandler.class));
}
Aggregations