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.redisson.command.RedisExecutor.java

License:Apache License

private void checkWriteFuture(ChannelFuture future, RPromise<R> attemptPromise, RedisConnection connection) {
    if (future.isCancelled() || attemptPromise.isDone()) {
        return;//  w  w  w  . j  a va 2  s .c  om
    }

    if (!future.isSuccess()) {
        exception = new WriteRedisConnectionException(
                "Unable to send command! Node source: " + source + ", connection: " + connection + ", command: "
                        + LogHelper.toString(command, params) + " after " + attempt + " retry attempts",
                future.cause());
        if (attempt == attempts) {
            if (!attemptPromise.tryFailure(exception)) {
                log.error(exception.getMessage());
            }
        }
        return;
    }

    timeout.cancel();

    long timeoutTime = responseTimeout;
    if (command != null && (RedisCommands.BLOCKING_COMMAND_NAMES.contains(command.getName())
            || RedisCommands.BLOCKING_COMMANDS.contains(command))) {
        Long popTimeout = null;
        if (RedisCommands.BLOCKING_COMMANDS.contains(command)) {
            boolean found = false;
            for (Object param : params) {
                if (found) {
                    popTimeout = Long.valueOf(param.toString()) / 1000;
                    break;
                }
                if ("BLOCK".equals(param)) {
                    found = true;
                }
            }
        } else {
            popTimeout = Long.valueOf(params[params.length - 1].toString());
        }

        handleBlockingOperations(attemptPromise, connection, popTimeout);
        if (popTimeout == 0) {
            return;
        }
        timeoutTime += popTimeout * 1000;
        // add 1 second due to issue https://github.com/antirez/redis/issues/874
        timeoutTime += 1000;
    }

    long timeoutAmount = timeoutTime;
    TimerTask timeoutTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attempt < attempts) {
                if (!attemptPromise.cancel(false)) {
                    return;
                }

                attempt++;
                if (log.isDebugEnabled()) {
                    log.debug("attempt {} for command {} and params {}", attempt, command,
                            LogHelper.toString(params));
                }

                mainPromiseListener = null;

                execute();
                return;
            }

            attemptPromise.tryFailure(new RedisResponseTimeoutException("Redis server response timeout ("
                    + timeoutAmount + " ms) occured" + " after " + attempts + " retry attempts. Command: "
                    + LogHelper.toString(command, params) + ", channel: " + connection.getChannel()));
        }
    };

    timeout = connectionManager.newTimeout(timeoutTask, timeoutTime, TimeUnit.MILLISECONDS);
}

From source file:org.redisson.CommandBatchExecutorService.java

License:Apache License

public void execute(final Entry entry, final int slot, final Promise<Void> mainPromise,
        final AtomicInteger slots, final int attempt) {
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.setFailure(new IllegalStateException("Redisson is shutdown"));
        return;/*from w  w w .j a va 2s.c o m*/
    }

    final Promise<Void> attemptPromise = connectionManager.newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                attemptPromise.setFailure(ex.get());
                return;
            }
            attemptPromise.cancel(true);

            int count = attempt + 1;
            execute(entry, slot, mainPromise, slots, count);
        }
    };

    try {
        org.redisson.client.RedisConnection connection;
        if (entry.isReadOnlyMode()) {
            connection = connectionManager.connectionReadOp(slot);
        } else {
            connection = connectionManager.connectionWriteOp(slot);
        }

        ArrayList<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(entry.getCommands().size());
        for (CommandEntry c : entry.getCommands()) {
            list.add(c.getCommand());
        }
        ChannelFuture future = connection.send(new CommandsData(attemptPromise, list));

        ex.set(new RedisTimeoutException());
        final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS);

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    timeout.cancel();
                    ex.set(new WriteRedisConnectionException("channel: " + future.channel() + " closed"));
                    connectionManager.getTimer().newTimeout(retryTimerTask,
                            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                }
            }
        });

        if (entry.isReadOnlyMode()) {
            attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout));
        } else {
            attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout));
        }
    } catch (RedisException e) {
        ex.set(e);
        connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    attemptPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                execute(entry, ex.getSlot(), mainPromise, slots, attempt);
                return;
            }

            if (future.isSuccess()) {
                if (slots.decrementAndGet() == 0) {
                    mainPromise.setSuccess(future.getNow());
                }
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

From source file:org.redisson.CommandExecutorService.java

License:Apache License

protected <V, R> void async(final boolean readOnlyMode, final int slot,
        final MultiDecoder<Object> messageDecoder, final Codec codec, final RedisCommand<V> command,
        final Object[] params, final Promise<R> mainPromise, final int attempt) {
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.setFailure(new IllegalStateException("Redisson is shutdown"));
        return;/* w  ww  . java2s  .  c  om*/
    }

    final Promise<R> attemptPromise = connectionManager.newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                attemptPromise.setFailure(ex.get());
                return;
            }
            if (!attemptPromise.cancel(false)) {
                return;
            }

            int count = attempt + 1;
            async(readOnlyMode, slot, messageDecoder, codec, command, params, mainPromise, count);
        }
    };

    try {
        org.redisson.client.RedisConnection connection;
        if (readOnlyMode) {
            connection = connectionManager.connectionReadOp(slot);
        } else {
            connection = connectionManager.connectionWriteOp(slot);
        }
        log.debug("getting connection for command {} via slot {} using {}", command, slot,
                connection.getRedisClient().getAddr());
        ChannelFuture future = connection
                .send(new CommandData<V, R>(attemptPromise, messageDecoder, codec, command, params));

        ex.set(new RedisTimeoutException());
        final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS);

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    timeout.cancel();
                    ex.set(new WriteRedisConnectionException("Can't send command: " + command + ", params: "
                            + params + ", channel: " + future.channel(), future.cause()));
                    connectionManager.getTimer().newTimeout(retryTimerTask,
                            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                }
            }
        });

        if (readOnlyMode) {
            attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout));
        } else {
            attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout));
        }
    } catch (RedisException e) {
        ex.set(e);
        connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    attemptPromise.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }
            // TODO cancel timeout

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                connectionManager.getTimer().newTimeout(retryTimerTask,
                        connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                async(readOnlyMode, ex.getSlot(), messageDecoder, codec, command, params, mainPromise, attempt);
                return;
            }

            if (future.isSuccess()) {
                mainPromise.setSuccess(future.getNow());
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

From source file:org.robotninjas.protobuf.netty.server.RpcServer.java

License:Open Source License

@Override
protected void doStart() {
    try {//from  www .j  a va2s  .c  om
        ChannelFuture f = bootstrap.bind(address);
        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    Channel serverChannel = future.channel();
                    allChannels.add(serverChannel);
                    notifyStarted();
                } else {
                    notifyFailed(future.cause());
                }
            }
        });
    } catch (Throwable t) {
        notifyFailed(t);
        Throwables.propagate(t);
    }
}

From source file:org.scache.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient 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<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from  ww w . j a  v  a 2  s.  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());
    }

    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.scache.network.server.TransportRequestHandler.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.
 *//*from  w w  w. j a v a  2 s.c  o m*/
private 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();
            }
        }
    });
}

From source file:org.server.core.netty.tcp.BaseConnector.java

License:Apache License

/**
 * //  ww w.java 2 s  . co  m
 * ?
 * 
 * @param future
 *            ?
 * 
 * @param retryCount
 *            ?
 */
protected void connectFinalCallback(ChannelFuture future, int retryCount) {
    // close before channel
    closeChannel();
    // assignment new channel
    channel = (NioSocketChannel) future.channel();
    // call the event
    safeCallHandle(h -> h.onConnectFinish(future.isSuccess(), channel, future.cause(), retryCount));
}

From source file:org.spongepowered.lantern.LanternServer.java

License:MIT License

public void bind() throws BindException {
    SocketAddress address = getBindAddress();

    SpongeImpl.getLogger().info("Binding to address: " + address + "...");
    ChannelFuture future = networkServer.bind(address);
    Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        Throwable cause = future.cause();
        if (cause instanceof BindException) {
            throw (BindException) cause;
        }/*from w  w w. j a va2s .  c  o  m*/
        throw new RuntimeException("Failed to bind to address", cause);
    }

    SpongeImpl.getLogger().info("Successfully bound to: " + channel.localAddress());
}

From source file:org.spout.engine.SpoutClient.java

License:Open Source License

private boolean connnect() {
    // Connect to server to establish session
    Protocol protocol = null;/*from   www.  ja  va  2  s .  c om*/
    if (getArguments().protocol != null) {
        protocol = Protocol.getProtocol(getArguments().protocol);
    }
    if (protocol == null) {
        protocol = Protocol.getProtocol("Spout");
    }
    String address;
    if (getArguments().server == null) {
        address = "localhost";
    } else {
        address = getArguments().server;
    }
    int port = getArguments().port != -1 ? getArguments().port : protocol.getDefaultPort();
    PortBindingImpl binding = new PortBindingImpl(protocol, new InetSocketAddress(address, port));
    ChannelFuture connect = bootstrap.connect(binding.getAddress());
    try {
        connect.await(10, TimeUnit.SECONDS);
    } catch (InterruptedException ex) {
        getLogger().log(Level.SEVERE, "Connection took too long! Cancelling connect and stopping engine!");
        stop();
        return false;
    }

    Channel channel = connect.channel();
    if (!connect.isSuccess()) {
        getLogger().log(Level.SEVERE, "Could not connect to " + binding, connect.cause());
        return false;
    }

    getLogger().log(Level.INFO,
            "Connected to " + address + ":" + port + " with protocol " + protocol.getName());
    CommonHandler handler = channel.pipeline().get(CommonHandler.class);
    SpoutClientSession session = new SpoutClientSession(this, channel, protocol);
    handler.setSession(session);

    Class<? extends PlayerNetworkComponent> network = session.getProtocol().getClientNetworkComponent(session);
    final SpoutClientPlayer p = new SpoutClientPlayer(this, network, "Spouty",
            new Transform().setPosition(new Point(getWorld(), 1, 200, 1)));
    session.setPlayer(p);
    p.getNetwork().setSession(session);
    session.getProtocol().initializeClientSession(session);
    player.set(p);
    return true;
}

From source file:org.spout.vanilla.protocol.rcon.RemoteConnectionServer.java

License:Open Source License

public void close() throws IOException {
    ChannelGroupFuture f = group.close().awaitUninterruptibly();
    if (!f.isSuccess()) {
        for (ChannelFuture future : f) {
            if (!future.isSuccess()) {
                throw new IOException(future.cause());
            }/*from ww  w.  ja v  a 2s  .  c om*/
        }
    }
    bootstrap.group().shutdownGracefully();
}