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:alluxio.client.netty.NettyUnderFileSystemBlockReader.java

License:Apache License

@Override
public ByteBuffer read(InetSocketAddress address, long blockId, long offset, long length, long sessionId,
        boolean noCache) throws IOException {
    Channel channel = null;/*from  w  w  w  .j av  a  2  s  . c  om*/
    ClientHandler clientHandler = null;
    Metrics.NETTY_UFS_BLOCK_READ_OPS.inc();
    try {
        channel = mContext.acquireNettyChannel(address);
        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 RPCUnderFileSystemBlockReadRequest(blockId, offset, length, sessionId, noCache));
        channelFuture = channelFuture.sync();
        if (channelFuture.isDone() && !channelFuture.isSuccess()) {
            LOG.error("Failed to read from %s for block %d with error %s.", address.toString(), blockId,
                    channelFuture.cause());
            throw new IOException(channelFuture.cause());
        }

        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);

        switch (response.getType()) {
        case RPC_BLOCK_READ_RESPONSE:
            RPCBlockReadResponse blockResponse = (RPCBlockReadResponse) response;
            LOG.debug("Data {} from machine {} received", blockId, address);

            RPCResponse.Status status = blockResponse.getStatus();
            if (status == RPCResponse.Status.SUCCESS) {
                // always clear the previous response before reading another one
                close();
                mReadResponse = blockResponse;
                return blockResponse.getPayloadDataBuffer().getReadOnlyByteBuffer();
            }
            throw new IOException(status.getMessage() + " response: " + blockResponse);
        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_READ_RESPONSE));
        }
    } catch (Exception e) {
        Metrics.NETTY_UFS_BLOCK_READ_FAILURES.inc();
        try {
            if (channel != null) {
                channel.close().sync();
            }
        } catch (InterruptedException ee) {
            throw new RuntimeException(ee);
        }
        throw new IOException(e);
    } finally {
        if (clientHandler != null) {
            clientHandler.removeListeners();
        }
        if (channel != null) {
            mContext.releaseNettyChannel(address, channel);
        }
    }
}

From source file:alluxio.network.connection.NettyChannelPool.java

License:Apache License

/**
 * Creates a netty channel instance.//w  w  w. j a v  a 2s  . c  o m
 *
 * @return the channel created
 * @throws IOException if it fails to create a channel
 */
@Override
protected Channel createNewResource() throws IOException {
    Bootstrap bs;
    try {
        bs = mBootstrap.clone();
    } catch (Exception e) {
        // No exception should happen here.
        throw Throwables.propagate(e);
    }
    try {
        ChannelFuture channelFuture = bs.connect().sync();
        if (channelFuture.isSuccess()) {
            LOG.info("Created netty channel with netty bootstrap {}.", mBootstrap);
            return channelFuture.channel();
        } else {
            LOG.error("Failed to create netty channel with netty bootstrap {} and error {}.", mBootstrap,
                    channelFuture.cause().getMessage());
            throw new IOException(channelFuture.cause());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:alluxio.network.netty.NettyChannelPool.java

License:Apache License

/**
 * Creates a netty channel instance./*  w  w w.  j  a v  a2s.c  om*/
 *
 * @return the channel created
 */
@Override
protected Channel createNewResource() throws IOException {
    Bootstrap bs;
    bs = mBootstrap.clone();
    try {
        ChannelFuture channelFuture = bs.connect().sync();
        if (channelFuture.isSuccess()) {
            LOG.info("Created netty channel with netty bootstrap {}.", mBootstrap);
            return channelFuture.channel();
        } else {
            LOG.error("Failed to create netty channel with netty bootstrap {} and error {}.", mBootstrap,
                    channelFuture.cause().getMessage());
            throw new UnavailableException(channelFuture.cause());
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CanceledException(e);
    }
}

From source file:alluxio.network.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits for a response.
 *
 * @param context the netty RPC context//  ww  w .j  a  v a2s.  c  o m
 * @param request the RPC request
 * @return the RPC response
 */
public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    final Promise<ProtoMessage> promise = channel.eventLoop().newPromise();
    channel.pipeline().addLast(new RPCHandler(promise));
    channel.writeAndFlush(new RPCProtoMessage(request)).addListener((ChannelFuture future) -> {
        if (future.cause() != null) {
            future.channel().close();
            promise.tryFailure(future.cause());
        }
    });
    ProtoMessage message;
    try {
        message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException | TimeoutException e) {
        CommonUtils.closeChannel(channel);
        throw new IOException(e);
    } catch (InterruptedException e) {
        CommonUtils.closeChannel(channel);
        throw new RuntimeException(e);
    } finally {
        if (channel.isOpen()) {
            channel.pipeline().removeLast();
        }
    }
    if (message.isResponse()) {
        CommonUtils.unwrapResponseFrom(message.asResponse(), context.getChannel());
    }
    return message;
}

From source file:alluxio.network.netty.NettyRPC.java

License:Apache License

/**
 * Sends a request and waits until the request is flushed to network. The caller of this method
 * should expect no response from the server and hence the service handler on server side should
 * not return any response or there will be issues. This method is typically used for RPCs
 * providing best efforts (e.g., async cache).
 *
 * @param context the netty RPC context/*w w  w  .j a va2s  . c om*/
 * @param request the RPC request
 */
public static void fireAndForget(final NettyRPCContext context, ProtoMessage request) throws IOException {
    Channel channel = Preconditions.checkNotNull(context.getChannel());
    // Not really using the atomicity of flushed, but use it as a wrapper of boolean that is final,
    // and can change value.
    final AtomicBoolean flushed = new AtomicBoolean(false);
    channel.writeAndFlush(new RPCProtoMessage(request)).addListener((ChannelFuture future) -> {
        if (future.cause() != null) {
            future.channel().close();
        }
        flushed.set(true);
        synchronized (flushed) {
            flushed.notify();
        }
    });
    try {
        synchronized (flushed) {
            while (!flushed.get()) {
                flushed.wait();
            }
        }
    } catch (InterruptedException e) {
        CommonUtils.closeChannel(channel);
        throw new RuntimeException(e);
    }
}

From source file:c5db.control.ControlService.java

License:Apache License

private void startHttpRpc() {
    try {//  w  w  w  .j a  va2  s.c  o  m
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        ServerBootstrap serverBootstrap1 = serverBootstrap.group(acceptConnectionGroup, ioWorkerGroup)
                .channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        //              pipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG));
                        pipeline.addLast("http-server", new HttpServerCodec());
                        pipeline.addLast("aggregator",
                                new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));

                        pipeline.addLast("encode", new ServerHttpProtostuffEncoder());
                        pipeline.addLast("decode", new ServerHttpProtostuffDecoder());

                        pipeline.addLast("translate", new ServerDecodeCommandRequest());

                        pipeline.addLast("inc-messages", new MessageHandler());
                    }
                });

        serverBootstrap.bind(modulePort).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // yay
                    listenChannel = future.channel();
                    notifyStarted();
                } else {
                    LOG.error("Unable to bind to port {}", modulePort);
                    notifyFailed(future.cause());
                }
            }
        });
    } catch (Exception e) {
        notifyFailed(e);
    }
}

From source file:c5db.control.SimpleControlClient.java

License:Apache License

public ListenableFuture<CommandReply> sendRequest(CommandRpcRequest<?> request,
        InetSocketAddress remoteAddress) {
    SettableFuture<CommandReply> replyMessageFuture = SettableFuture.create();
    ChannelFuture connectFuture = client.connect(remoteAddress);
    connectFuture.addListener(new ChannelFutureListener() {
        @Override//from  w  w w.j  a  v  a2  s .  c  om
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().pipeline().addLast(new SimpleChannelInboundHandler<CommandReply>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, CommandReply msg) throws Exception {
                        replyMessageFuture.set(msg);
                        ctx.channel().close();
                    }
                });

                // connected is fine, flush message:
                future.channel().writeAndFlush(request);
            } else {
                replyMessageFuture.setException(future.cause());
                future.channel().close();
            }
        }
    });

    return replyMessageFuture;
}

From source file:c5db.regionserver.RegionServerService.java

License:Apache License

@Override
protected void doStart() {
    fiber.start();// www  .  j a  v  a  2s  .c  o  m

    fiber.execute(() -> {
        // we need the tablet module:
        ListenableFuture<C5Module> f = server.getModule(ModuleType.Tablet);
        Futures.addCallback(f, new FutureCallback<C5Module>() {
            @Override
            public void onSuccess(final C5Module result) {
                tabletModule = (TabletModule) result;
                bootstrap.group(acceptGroup, workerGroup).option(ChannelOption.SO_REUSEADDR, true)
                        .childOption(ChannelOption.TCP_NODELAY, true).channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast("http-server-codec", new HttpServerCodec());
                                p.addLast("http-agg",
                                        new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("websocket-agg",
                                        new WebSocketFrameAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("decoder", new WebsocketProtostuffDecoder("/websocket"));
                                p.addLast("encoder", new WebsocketProtostuffEncoder());
                                p.addLast("handler", new RegionServerHandler(RegionServerService.this));
                            }
                        });

                bootstrap.bind(port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            listenChannel = future.channel();
                            notifyStarted();
                        } else {
                            LOG.error("Unable to find Region Server to {} {}", port, future.cause());
                            notifyFailed(future.cause());
                        }
                    }
                });
            }

            @Override
            public void onFailure(Throwable t) {
                notifyFailed(t);
            }
        }, fiber);
    });
}

From source file:ccwihr.client.t2.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 *//* w w w .  ja v a 2 s  .c  o m*/
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}

From source file:club.lovety.xy.netty.test.UptimeClient.java

License:Apache License

static void connect(Bootstrap b) {
    b.connect().addListener(new ChannelFutureListener() {
        @Override//from   www .j  av a2 s. com
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() != null) {
                handler.startTime = -1;
                handler.println("Failed to connect: " + future.cause());
            }
        }
    });
}