Search in sources :

Example 36 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project async-http-client by AsyncHttpClient.

the class ChannelManager method getClientStats.

public ClientStats getClientStats() {
    Map<String, Long> totalConnectionsPerHost = openChannels.stream().map(Channel::remoteAddress).filter(a -> a.getClass() == InetSocketAddress.class).map(a -> (InetSocketAddress) a).map(InetSocketAddress::getHostName).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    Map<String, Long> idleConnectionsPerHost = channelPool.getIdleChannelCountPerHost();
    Map<String, HostStats> statsPerHost = totalConnectionsPerHost.entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> {
        final long totalConnectionCount = entry.getValue();
        final long idleConnectionCount = idleConnectionsPerHost.getOrDefault(entry.getKey(), 0L);
        final long activeConnectionCount = totalConnectionCount - idleConnectionCount;
        return new HostStats(activeConnectionCount, idleConnectionCount);
    }));
    return new ClientStats(statsPerHost);
}
Also used : TooManyConnectionsException(org.asynchttpclient.exception.TooManyConnectionsException) ChannelPoolPartitioning(org.asynchttpclient.channel.ChannelPoolPartitioning) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) TooManyConnectionsPerHostException(org.asynchttpclient.exception.TooManyConnectionsPerHostException) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) LoggerFactory(org.slf4j.LoggerFactory) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) WebSocket08FrameDecoder(io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) AsyncHttpClientConfig(org.asynchttpclient.AsyncHttpClientConfig) Map(java.util.Map) ThreadFactory(java.util.concurrent.ThreadFactory) ChannelGroup(io.netty.channel.group.ChannelGroup) ChannelInitializer(io.netty.channel.ChannelInitializer) NettyResponseFuture(org.asynchttpclient.netty.NettyResponseFuture) WebSocketHandler(org.asynchttpclient.netty.handler.WebSocketHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AsyncHandler(org.asynchttpclient.AsyncHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelPool(org.asynchttpclient.channel.ChannelPool) PoolAlreadyClosedException(org.asynchttpclient.exception.PoolAlreadyClosedException) SSLException(javax.net.ssl.SSLException) LogLevel(io.netty.handler.logging.LogLevel) SslHandler(io.netty.handler.ssl.SslHandler) Entry(java.util.Map.Entry) Timer(io.netty.util.Timer) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) AsyncHttpClientHandler(org.asynchttpclient.netty.handler.AsyncHttpClientHandler) Function(java.util.function.Function) ClientStats(org.asynchttpclient.ClientStats) SSLEngine(javax.net.ssl.SSLEngine) NoopChannelPool(org.asynchttpclient.channel.NoopChannelPool) HttpHandler(org.asynchttpclient.netty.handler.HttpHandler) SslEngineFactory(org.asynchttpclient.SslEngineFactory) WebSocketFrameAggregator(io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator) ChannelFactory(io.netty.channel.ChannelFactory) WebSocket08FrameEncoder(io.netty.handler.codec.http.websocketx.WebSocket08FrameEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) Semaphore(java.util.concurrent.Semaphore) DefaultSslEngineFactory(org.asynchttpclient.netty.ssl.DefaultSslEngineFactory) IOException(java.io.IOException) OioEventLoopGroup(io.netty.channel.oio.OioEventLoopGroup) HostStats(org.asynchttpclient.HostStats) ProxyServer(org.asynchttpclient.proxy.ProxyServer) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) AsyncHandlerExtensions(org.asynchttpclient.handler.AsyncHandlerExtensions) OnLastHttpContentCallback(org.asynchttpclient.netty.OnLastHttpContentCallback) Uri(org.asynchttpclient.uri.Uri) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NettyRequestSender(org.asynchttpclient.netty.request.NettyRequestSender) ThrowableUtil.unknownStackTrace(io.netty.util.internal.ThrowableUtil.unknownStackTrace) ClientStats(org.asynchttpclient.ClientStats) Channel(io.netty.channel.Channel) HostStats(org.asynchttpclient.HostStats)

Example 37 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project async-http-client by AsyncHttpClient.

the class AsyncHttpClientHandler method channelInactive.

public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if (requestSender.isClosed())
        return;
    Channel channel = ctx.channel();
    channelManager.removeAll(channel);
    Object attribute = Channels.getAttribute(channel);
    logger.debug("Channel Closed: {} with attribute {}", channel, attribute);
    if (attribute instanceof StreamedResponsePublisher) {
        // setting `attribute` to be the underlying future so that the retry
        // logic can kick-in
        attribute = ((StreamedResponsePublisher) attribute).future();
    }
    if (attribute instanceof OnLastHttpContentCallback) {
        OnLastHttpContentCallback callback = (OnLastHttpContentCallback) attribute;
        Channels.setAttribute(channel, callback.future());
        callback.call();
    } else if (attribute instanceof NettyResponseFuture<?>) {
        NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
        future.touch();
        if (hasIOExceptionFilters && requestSender.applyIoExceptionFiltersAndReplayRequest(future, ChannelClosedException.INSTANCE, channel))
            return;
        handleChannelInactive(future);
        requestSender.handleUnexpectedClosedChannel(channel, future);
    }
}
Also used : Channel(io.netty.channel.Channel) OnLastHttpContentCallback(org.asynchttpclient.netty.OnLastHttpContentCallback) NettyResponseFuture(org.asynchttpclient.netty.NettyResponseFuture)

Example 38 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project async-http-client by AsyncHttpClient.

the class NettyRequestSender method sendRequestThroughSslProxy.

/**
     * Using CONNECT depends on wither we can fetch a valid channel or not Loop until we get a valid channel from the pool and it's still valid once the request is built @
     */
@SuppressWarnings("unused")
private <//
T> //
ListenableFuture<T> sendRequestThroughSslProxy(//
Request request, //
AsyncHandler<T> asyncHandler, //
NettyResponseFuture<T> future, //
boolean performingNextRequest, ProxyServer proxyServer) {
    NettyResponseFuture<T> newFuture = null;
    for (int i = 0; i < 3; i++) {
        Channel channel = getOpenChannel(future, request, proxyServer, asyncHandler);
        if (Channels.isChannelValid(channel))
            if (newFuture == null)
                newFuture = newNettyRequestAndResponseFuture(request, asyncHandler, future, proxyServer, false);
        if (Channels.isChannelValid(channel))
            // gain
            return sendRequestWithOpenChannel(request, proxyServer, newFuture, asyncHandler, channel);
        else
            // pool is empty
            break;
    }
    newFuture = newNettyRequestAndResponseFuture(request, asyncHandler, future, proxyServer, true);
    return sendRequestWithNewChannel(request, proxyServer, newFuture, asyncHandler, performingNextRequest);
}
Also used : EXPECT(io.netty.handler.codec.http.HttpHeaderNames.EXPECT) Channel(io.netty.channel.Channel)

Example 39 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project async-http-client by AsyncHttpClient.

the class NettyChannelConnector method connect0.

private void connect0(Bootstrap bootstrap, final NettyConnectListener<?> connectListener, InetSocketAddress remoteAddress) {
    //
    bootstrap.connect(remoteAddress, localAddress).addListener(new SimpleChannelFutureListener() {

        @Override
        public void onSuccess(Channel channel) {
            if (asyncHandlerExtensions != null) {
                asyncHandlerExtensions.onTcpConnectSuccess(remoteAddress, channel);
            }
            connectListener.onSuccess(channel, remoteAddress);
        }

        @Override
        public void onFailure(Channel channel, Throwable t) {
            if (asyncHandlerExtensions != null)
                asyncHandlerExtensions.onTcpConnectFailure(remoteAddress, t);
            boolean retry = pickNextRemoteAddress();
            if (retry)
                NettyChannelConnector.this.connect(bootstrap, connectListener);
            else
                connectListener.onFailure(channel, t);
        }
    });
}
Also used : Channel(io.netty.channel.Channel) SimpleChannelFutureListener(org.asynchttpclient.netty.SimpleChannelFutureListener)

Example 40 with Channel

use of org.apache.flink.shaded.netty4.io.netty.channel.Channel in project alluxio by Alluxio.

the class NettyRemoteBlockWriter method write.

@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
    Channel channel = null;
    ClientHandler clientHandler = null;
    Metrics.NETTY_BLOCK_WRITE_OPS.inc();
    try {
        channel = mContext.acquireNettyChannel(mAddress);
        if (!(channel.pipeline().last() instanceof ClientHandler)) {
            channel.pipeline().addLast(new ClientHandler());
        }
        clientHandler = (ClientHandler) channel.pipeline().last();
        SingleResponseListener listener = new SingleResponseListener();
        clientHandler.addListener(listener);
        ChannelFuture channelFuture = channel.writeAndFlush(new RPCBlockWriteRequest(mSessionId, mBlockId, mWrittenBytes, length, new DataByteArrayChannel(bytes, offset, length))).sync();
        if (channelFuture.isDone() && !channelFuture.isSuccess()) {
            LOG.error("Failed to write to %s for block %d with error %s.", mAddress.toString(), mBlockId, channelFuture.cause());
            throw new IOException(channelFuture.cause());
        }
        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);
        switch(response.getType()) {
            case RPC_BLOCK_WRITE_RESPONSE:
                RPCBlockWriteResponse resp = (RPCBlockWriteResponse) response;
                RPCResponse.Status status = resp.getStatus();
                LOG.debug("status: {} from remote machine {} received", status, mAddress);
                if (status != RPCResponse.Status.SUCCESS) {
                    throw new IOException(ExceptionMessage.BLOCK_WRITE_ERROR.getMessage(mBlockId, mSessionId, mAddress, status.getMessage()));
                }
                mWrittenBytes += length;
                break;
            case RPC_ERROR_RESPONSE:
                RPCErrorResponse error = (RPCErrorResponse) response;
                throw new IOException(error.getStatus().getMessage());
            default:
                throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(), RPCMessage.Type.RPC_BLOCK_WRITE_RESPONSE));
        }
    } catch (Exception e) {
        Metrics.NETTY_BLOCK_WRITE_FAILURES.inc();
        try {
            // TODO(peis): We should not close the channel unless it is an exception caused by network.
            if (channel != null) {
                channel.close().sync();
            }
        } catch (InterruptedException ee) {
            Throwables.propagate(ee);
        }
        throw new IOException(e);
    } finally {
        if (clientHandler != null) {
            clientHandler.removeListeners();
        }
        if (channel != null) {
            mContext.releaseNettyChannel(mAddress, channel);
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RPCBlockWriteRequest(alluxio.network.protocol.RPCBlockWriteRequest) Channel(io.netty.channel.Channel) DataByteArrayChannel(alluxio.network.protocol.databuffer.DataByteArrayChannel) RPCResponse(alluxio.network.protocol.RPCResponse) IOException(java.io.IOException) IOException(java.io.IOException) DataByteArrayChannel(alluxio.network.protocol.databuffer.DataByteArrayChannel) RPCErrorResponse(alluxio.network.protocol.RPCErrorResponse) RPCBlockWriteResponse(alluxio.network.protocol.RPCBlockWriteResponse)

Aggregations

Channel (io.netty.channel.Channel)796 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)212 Test (org.junit.Test)195 Bootstrap (io.netty.bootstrap.Bootstrap)192 ChannelFuture (io.netty.channel.ChannelFuture)189 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)175 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)172 InetSocketAddress (java.net.InetSocketAddress)159 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)144 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)136 EventLoopGroup (io.netty.channel.EventLoopGroup)134 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)130 IOException (java.io.IOException)124 ByteBuf (io.netty.buffer.ByteBuf)108 CountDownLatch (java.util.concurrent.CountDownLatch)97 ChannelPipeline (io.netty.channel.ChannelPipeline)93 LocalChannel (io.netty.channel.local.LocalChannel)93 SocketChannel (io.netty.channel.socket.SocketChannel)91 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)90 LocalServerChannel (io.netty.channel.local.LocalServerChannel)89