Example usage for io.netty.channel ChannelFuture cause

List of usage examples for io.netty.channel ChannelFuture cause

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture cause.

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:org.apache.rocketmq.filtersrv.processor.DefaultRequestProcessor.java

License:Apache License

private void returnResponse(final String group, final String topic, ChannelHandlerContext ctx,
        final RemotingCommand response, final List<MessageExt> msgList) {
    if (null != msgList) {
        ByteBuffer[] msgBufferList = new ByteBuffer[msgList.size()];
        int bodyTotalSize = 0;
        for (int i = 0; i < msgList.size(); i++) {
            try {
                msgBufferList[i] = messageToByteBuffer(msgList.get(i));
                bodyTotalSize += msgBufferList[i].capacity();
            } catch (Exception e) {
                log.error("messageToByteBuffer UnsupportedEncodingException", e);
            }/*  w w  w.  j a  v a  2  s.com*/
        }

        ByteBuffer body = ByteBuffer.allocate(bodyTotalSize);
        for (ByteBuffer bb : msgBufferList) {
            bb.flip();
            body.put(bb);
        }

        response.setBody(body.array());

        this.filtersrvController.getFilterServerStatsManager().incGroupGetNums(group, topic, msgList.size());

        this.filtersrvController.getFilterServerStatsManager().incGroupGetSize(group, topic, bodyTotalSize);
    }

    try {
        ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.error("FilterServer response to " + future.channel().remoteAddress() + " failed",
                            future.cause());
                    log.error(response.toString());
                }
            }
        });
    } catch (Throwable e) {
        log.error("FilterServer process request over, but response failed", e);
        log.error(response.toString());
    }
}

From source file:org.apache.rocketmq.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    final int opaque = request.getOpaque();

    try {// w  w w  .  j a va 2s .com
        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null);
        this.responseTable.put(opaque, responseFuture);
        final SocketAddress addr = channel.remoteAddress();
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(opaque);
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                PLOG.warn("send a request command to channel <" + addr + "> failed.");
            }
        });

        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
            } else {
                throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(opaque);
    }
}

From source file:org.apache.rocketmq.remoting.netty.NettyRemotingClient.java

License:Apache License

private Channel createChannel(final String addr) throws InterruptedException {
    ChannelWrapper cw = this.channelTables.get(addr);
    if (cw != null && cw.isOK()) {
        return cw.getChannel();
    }/*from   w w  w.  ja  va 2  s.c  o  m*/

    if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
        try {
            boolean createNewConnection = false;
            cw = this.channelTables.get(addr);
            if (cw != null) {

                if (cw.isOK()) {
                    return cw.getChannel();
                } else if (!cw.getChannelFuture().isDone()) {
                    createNewConnection = false;
                } else {
                    this.channelTables.remove(addr);
                    createNewConnection = true;
                }
            } else {
                createNewConnection = true;
            }

            if (createNewConnection) {
                ChannelFuture channelFuture = this.bootstrap.connect(RemotingHelper.string2SocketAddress(addr));
                log.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
                cw = new ChannelWrapper(channelFuture);
                this.channelTables.put(addr, cw);
            }
        } catch (Exception e) {
            log.error("createChannel: create channel exception", e);
        } finally {
            this.lockChannelTables.unlock();
        }
    } else {
        log.warn("createChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
    }

    if (cw != null) {
        ChannelFuture channelFuture = cw.getChannelFuture();
        if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
            if (cw.isOK()) {
                log.info("createChannel: connect remote host[{}] success, {}", addr, channelFuture.toString());
                return cw.getChannel();
            } else {
                log.warn("createChannel: connect remote host[" + addr + "] failed, " + channelFuture.toString(),
                        channelFuture.cause());
            }
        } else {
            log.warn("createChannel: connect remote host[{}] timeout {}ms, {}", addr,
                    this.nettyClientConfig.getConnectTimeoutMillis(), channelFuture.toString());
        }
    }

    return null;
}

From source file:org.apache.spark.network.client.TransportClient.java

License:Apache License

/**
 * Sends an opaque message to the RpcHandler on the server-side. The callback will be invoked
 * with the server's response or upon any failure.
 *//*from   w  w w . j  a va 2  s  . co  m*/
public void sendRpc(byte[] message, final RpcResponseCallback callback) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.trace("Sending RPC to {}", serverAddr);

    final long requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());
    handler.addRpcRequest(requestId, callback);

    channel.writeAndFlush(new RpcRequest(requestId, message)).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                long timeTaken = System.currentTimeMillis() - startTime;
                logger.trace("Sending request {} to {} took {} ms", requestId, serverAddr, timeTaken);
            } else {
                String errorMsg = String.format("Failed to send RPC %s to %s: %s", requestId, serverAddr,
                        future.cause());
                logger.error(errorMsg, future.cause());
                handler.removeRpcRequest(requestId);
                channel.close();
                try {
                    callback.onFailure(new IOException(errorMsg, future.cause()));
                } catch (Exception e) {
                    logger.error("Uncaught exception in RPC response callback handler!", e);
                }
            }
        }
    });
}

From source file:org.apache.spark.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException, InterruptedException {
    logger.debug("Creating new connection to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    if (conf.receiveBuf() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, conf.receiveBuf());
    }//from w  w w. ja v  a  2  s  .  c  o  m

    if (conf.sendBuf() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, conf.sendBuf());
    }

    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.await(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:org.apache.spark.network.netty.NettyTransportClient.java

License:Apache License

/**
 * Requests a single chunk from the remote side, from the pre-negotiated streamId.
 *
 * Chunk indices go from 0 onwards. It is valid to request the same chunk multiple times, though
 * some streams may not support this./*from w  w  w.  ja v  a2  s .c  om*/
 *
 * Multiple fetchChunk requests may be outstanding simultaneously, and the chunks are guaranteed
 * to be returned in the same order that they were requested, assuming only a single
 * TransportClient is used to fetch the chunks.
 *
 * @param streamId Identifier that refers to a stream in the remote StreamManager. This should
 *                 be agreed upon by client and server beforehand.
 * @param chunkIndex 0-based index of the chunk to fetch
 * @param callback Callback invoked upon successful receipt of chunk, or upon any failure.
 */
@Override
public void fetchChunk(long streamId, final int chunkIndex, final ChunkReceivedCallback callback) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.debug("Sending fetch chunk request {} to {}", chunkIndex, serverAddr);

    final StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex);
    handler.addFetchRequest(streamChunkId, callback);

    channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                long timeTaken = System.currentTimeMillis() - startTime;
                logger.trace("Sending request {} to {} took {} ms", streamChunkId, serverAddr, timeTaken);
            } else {
                String errorMsg = String.format("Failed to send request %s to %s: %s", streamChunkId,
                        serverAddr, future.cause());
                logger.error(errorMsg, future.cause());
                handler.removeFetchRequest(streamChunkId);
                channel.close();
                try {
                    callback.onFailure(chunkIndex, new IOException(errorMsg, future.cause()));
                } catch (Exception e) {
                    logger.error("Uncaught exception in RPC response callback handler!", e);
                }
            }
        }
    });
}

From source file:org.apache.spark.network.netty.NettyTransportClient.java

License:Apache License

/**
 * Request to stream the data with the given stream ID from the remote end.
 *
 * @param streamId The stream to fetch./*from  w  w w.  j av a2 s . c om*/
 * @param callback Object to call with the stream data.
 */
@Override
public void stream(final String streamId, final StreamCallback callback) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.debug("Sending stream request for {} to {}", streamId, serverAddr);

    // Need to synchronize here so that the callback is added to the queue and the RPC is
    // written to the socket atomically, so that callbacks are called in the right order
    // when responses arrive.
    synchronized (this) {
        handler.addStreamCallback(callback);
        channel.writeAndFlush(new StreamRequest(streamId)).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    long timeTaken = System.currentTimeMillis() - startTime;
                    logger.trace("Sending request for {} to {} took {} ms", streamId, serverAddr, timeTaken);
                } else {
                    String errorMsg = String.format("Failed to send request for %s to %s: %s", streamId,
                            serverAddr, future.cause());
                    logger.error(errorMsg, future.cause());
                    channel.close();
                    try {
                        callback.onFailure(streamId, new IOException(errorMsg, future.cause()));
                    } catch (Exception e) {
                        logger.error("Uncaught exception in RPC response callback handler!", e);
                    }
                }
            }
        });
    }
}

From source file:org.apache.spark.network.netty.NettyTransportClient.java

License:Apache License

/**
 * Sends an opaque message to the RpcHandler on the server-side. The callback will be invoked
 * with the server's response or upon any failure.
 *
 * @param message The message to send./*from   w ww . ja  v a2  s.  c  o  m*/
 * @param callback Callback to handle the RPC's reply.
 * @return The RPC's id.
 */
@Override
public long sendRpc(ByteBuffer message, final RpcResponseCallback callback) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.trace("Sending RPC to {}", serverAddr);

    final long requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());
    handler.addRpcRequest(requestId, callback);

    channel.writeAndFlush(new RpcRequest(requestId, new NioManagedBuffer(message)))
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        long timeTaken = System.currentTimeMillis() - startTime;
                        logger.trace("Sending request {} to {} took {} ms", requestId, serverAddr, timeTaken);
                    } else {
                        String errorMsg = String.format("Failed to send RPC %s to %s: %s", requestId,
                                serverAddr, future.cause());
                        logger.error(errorMsg, future.cause());
                        handler.removeRpcRequest(requestId);
                        channel.close();
                        try {
                            callback.onFailure(new IOException(errorMsg, future.cause()));
                        } catch (Exception e) {
                            logger.error("Uncaught exception in RPC response callback handler!", e);
                        }
                    }
                }
            });

    return requestId;
}

From source file:org.apache.spark.network.netty.NettyTransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private NettyTransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<NettyTransportClient> clientRef = new AtomicReference<NettyTransportClient>();
    final AtomicReference<Channel> channelRef = new AtomicReference<Channel>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from ww w .j av a 2s  . com*/
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    NettyTransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.debug("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}

From source file:org.apache.spark.network.netty.NettyTransportRequestHandler.java

License:Apache License

/**
 * Responds to a single message with some Encodable object. If a failure occurs while sending,
 * it will be logged and the channel closed.
 */// w w  w.ja  v a2  s  .c o m
public void respond(final Encodable result) {
    final String remoteAddress = channel.remoteAddress().toString();
    channel.writeAndFlush(result).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                logger.trace(String.format("Sent result %s to client %s", result, remoteAddress));
            } else {
                logger.error(String.format("Error sending result %s to %s; closing connection", result,
                        remoteAddress), future.cause());
                channel.close();
            }
        }
    });
}