Search in sources :

Example 16 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project ratpack by ratpack.

the class RequestActionSupport method addCommonResponseHandlers.

private void addCommonResponseHandlers(ChannelPipeline p, Downstream<? super T> downstream) throws Exception {
    if (channelKey.ssl && p.get(SSL_HANDLER_NAME) == null) {
        // this is added once because netty is not able to properly replace this handler on
        // pooled channels from request to request. Because a pool is unique to a uri,
        // doing this works, as subsequent requests would be passing in the same certs.
        p.addLast(SSL_HANDLER_NAME, createSslHandler());
    }
    p.addLast(CLIENT_CODEC_HANDLER_NAME, new HttpClientCodec(4096, 8192, requestConfig.responseMaxChunkSize, false));
    p.addLast(READ_TIMEOUT_HANDLER_NAME, new ReadTimeoutHandler(requestConfig.readTimeout.toNanos(), TimeUnit.NANOSECONDS));
    p.addLast(REDIRECT_HANDLER_NAME, new SimpleChannelInboundHandler<HttpObject>(false) {

        boolean redirected;

        HttpResponse response;

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            ctx.fireExceptionCaught(new PrematureChannelClosureException("Server " + requestConfig.uri + " closed the connection prematurely"));
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
            if (msg instanceof HttpResponse) {
                this.response = (HttpResponse) msg;
                int maxRedirects = requestConfig.maxRedirects;
                int status = response.status().code();
                String locationValue = response.headers().getAsString(HttpHeaderConstants.LOCATION);
                Action<? super RequestSpec> redirectConfigurer = RequestActionSupport.this.requestConfigurer;
                if (isRedirect(status) && redirectCount < maxRedirects && locationValue != null) {
                    final Function<? super ReceivedResponse, Action<? super RequestSpec>> onRedirect = requestConfig.onRedirect;
                    if (onRedirect != null) {
                        final Action<? super RequestSpec> onRedirectResult = onRedirect.apply(toReceivedResponse(response));
                        if (onRedirectResult == null) {
                            redirectConfigurer = null;
                        } else {
                            redirectConfigurer = redirectConfigurer.append(onRedirectResult);
                        }
                    }
                    if (redirectConfigurer != null) {
                        Action<? super RequestSpec> redirectRequestConfig = s -> {
                            if (status == 301 || status == 302) {
                                s.get();
                            }
                        };
                        redirectRequestConfig = redirectConfigurer.append(redirectRequestConfig);
                        URI locationUrl;
                        if (ABSOLUTE_PATTERN.matcher(locationValue).matches()) {
                            locationUrl = new URI(locationValue);
                        } else {
                            locationUrl = new URI(channelKey.ssl ? "https" : "http", null, channelKey.host, channelKey.port, locationValue, null, null);
                        }
                        onRedirect(locationUrl, redirectCount + 1, redirectRequestConfig).connect(downstream);
                        redirected = true;
                        dispose(ctx.pipeline(), response);
                    }
                }
            }
            if (!redirected) {
                ctx.fireChannelRead(msg);
            }
        }
    });
    if (requestConfig.decompressResponse) {
        p.addLast(DECOMPRESS_HANDLER_NAME, new HttpContentDecompressor());
    }
    addResponseHandlers(p, downstream);
}
Also used : Action(ratpack.func.Action) PrematureChannelClosureException(io.netty.handler.codec.PrematureChannelClosureException) ReceivedResponse(ratpack.http.client.ReceivedResponse) URI(java.net.URI) PrematureChannelClosureException(io.netty.handler.codec.PrematureChannelClosureException) ReadTimeoutException(io.netty.handler.timeout.ReadTimeoutException) SSLException(javax.net.ssl.SSLException) HttpClientReadTimeoutException(ratpack.http.client.HttpClientReadTimeoutException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Function(ratpack.func.Function) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) RequestSpec(ratpack.http.client.RequestSpec)

Example 17 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project JavaForFun by gumartinm.

the class ServicesConfig method webClientBuilder.

@Bean
public WebClient.Builder webClientBuilder() {
    ClientHttpConnector connector = new ReactorClientHttpConnector(options -> {
        options.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeOut).onChannelInit(channel -> {
            channel.pipeline().addLast(new ReadTimeoutHandler(readTimeOut, TimeUnit.MILLISECONDS));
            channel.pipeline().addLast(new WriteTimeoutHandler(writeTimeout, TimeUnit.MILLISECONDS));
            return true;
        });
    });
    WebClient.Builder webClientBuilder = WebClient.builder();
    return webClientBuilder.clientConnector(connector);
}
Also used : ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) WriteTimeoutHandler(io.netty.handler.timeout.WriteTimeoutHandler) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) WebClient(org.springframework.web.reactive.function.client.WebClient) ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) Bean(org.springframework.context.annotation.Bean)

Example 18 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project rskj by rsksmart.

the class Channel method init.

public void init(ChannelPipeline pipeline, String remoteId, boolean discoveryMode) {
    isActive = remoteId != null && !remoteId.isEmpty();
    pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(config.peerChannelReadTimeout(), TimeUnit.SECONDS));
    pipeline.addLast("handshakeHandler", handshakeHandler);
    this.discoveryMode = discoveryMode;
    if (discoveryMode) {
        // temporary key/nodeId to not accidentally smear our reputation with
        // unexpected disconnect
        handshakeHandler.generateTempKey();
    }
    handshakeHandler.setRemoteId(remoteId, this);
    messageCodec.setChannel(this);
    msgQueue.setChannel(this);
    p2pHandler.setMsgQueue(msgQueue);
    messageCodec.setP2pMessageFactory(new P2pMessageFactory());
}
Also used : P2pMessageFactory(org.ethereum.net.p2p.P2pMessageFactory) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Example 19 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project LanternServer by LanternPowered.

the class NetworkManager method init0.

@Override
protected ChannelFuture init0(SocketAddress address, boolean epoll) {
    this.bootstrap = new ServerBootstrap();
    // Take advantage of the fast thread local threads,
    // this is also provided by the default thread factory
    final ThreadFactory threadFactory = ThreadHelper.newFastThreadLocalThreadFactory(() -> "netty-" + threadCounter.getAndIncrement());
    this.bossGroup = createEventLoopGroup(epoll, threadFactory);
    this.workerGroup = createEventLoopGroup(epoll, threadFactory);
    this.socketAddress = address;
    return this.bootstrap.group(this.bossGroup, this.workerGroup).channel(getServerSocketChannelClass(epoll)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            final NetworkSession networkSession = new NetworkSession(ch, server, NetworkManager.this);
            final CodecContext codecContext = new SimpleCodecContext(new LanternByteBufferAllocator(ch.alloc()), ch, networkSession);
            pipeline.addLast(new ReadTimeoutHandler(NetworkSession.READ_TIMEOUT_SECONDS)).addLast(NetworkSession.LEGACY_PING, new LegacyProtocolHandler(networkSession)).addLast(NetworkSession.ENCRYPTION, NoopHandler.INSTANCE).addLast(NetworkSession.FRAMING, new MessageFramingHandler()).addLast(NetworkSession.COMPRESSION, NoopHandler.INSTANCE).addLast(NetworkSession.CODECS, new MessageCodecHandler(codecContext)).addLast(NetworkSession.PROCESSOR, new MessageProcessorHandler(codecContext)).addLast(NetworkSession.HANDLER, networkSession);
        }
    }).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true).bind(address);
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) SocketChannel(io.netty.channel.socket.SocketChannel) SimpleCodecContext(org.lanternpowered.server.network.message.codec.SimpleCodecContext) CodecContext(org.lanternpowered.server.network.message.codec.CodecContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) LegacyProtocolHandler(org.lanternpowered.server.network.pipeline.LegacyProtocolHandler) LanternByteBufferAllocator(org.lanternpowered.server.network.buffer.LanternByteBufferAllocator) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) MessageFramingHandler(org.lanternpowered.server.network.pipeline.MessageFramingHandler) SimpleCodecContext(org.lanternpowered.server.network.message.codec.SimpleCodecContext) MessageProcessorHandler(org.lanternpowered.server.network.pipeline.MessageProcessorHandler) MessageCodecHandler(org.lanternpowered.server.network.pipeline.MessageCodecHandler)

Example 20 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project graylog2-server by Graylog2.

the class HttpTransport method getCustomChildChannelHandlers.

@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getCustomChildChannelHandlers(MessageInput input) {
    final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>();
    if (idleWriterTimeout > 0) {
        // Install read timeout handler to close idle connections after a timeout.
        // This avoids dangling HTTP connections when the HTTP client does not close the connection properly.
        // For details see: https://github.com/Graylog2/graylog2-server/issues/3223#issuecomment-270350500
        handlers.put("read-timeout-handler", () -> new ReadTimeoutHandler(idleWriterTimeout, TimeUnit.SECONDS));
    }
    handlers.put("decoder", () -> new HttpRequestDecoder(DEFAULT_MAX_INITIAL_LINE_LENGTH, DEFAULT_MAX_HEADER_SIZE, maxChunkSize));
    handlers.put("decompressor", HttpContentDecompressor::new);
    handlers.put("encoder", HttpResponseEncoder::new);
    handlers.put("aggregator", () -> new HttpObjectAggregator(maxChunkSize));
    handlers.put("http-handler", () -> new HttpHandler(enableCors));
    handlers.putAll(super.getCustomChildChannelHandlers(input));
    return handlers;
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) HttpHandler(org.graylog2.inputs.transports.netty.HttpHandler) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) ChannelHandler(io.netty.channel.ChannelHandler) Callable(java.util.concurrent.Callable) LinkedHashMap(java.util.LinkedHashMap) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor)

Aggregations

ReadTimeoutHandler (io.netty.handler.timeout.ReadTimeoutHandler)26 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 ChannelHandler (io.netty.channel.ChannelHandler)6 ChannelPipeline (io.netty.channel.ChannelPipeline)6 LoggingHandler (io.netty.handler.logging.LoggingHandler)6 TimeUnit (java.util.concurrent.TimeUnit)6 Bootstrap (io.netty.bootstrap.Bootstrap)5 SocketChannel (io.netty.channel.socket.SocketChannel)5 Channel (io.netty.channel.Channel)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)4 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)4 IOException (java.io.IOException)4 InetSocketAddress (java.net.InetSocketAddress)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Connection (reactor.netty.Connection)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 ByteBuf (io.netty.buffer.ByteBuf)3 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)3 SslContext (io.netty.handler.ssl.SslContext)3 SSLException (javax.net.ssl.SSLException)3