Example usage for io.netty.channel ChannelFuture cancel

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

Introduction

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

Prototype

@Override
boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

If the cancellation was successful it will fail the future with a CancellationException .

Usage

From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java

License:Open Source License

/**
 * Wraps given {@link ChannelFuture} to ensure the event loops
 * shut down gracefully./*  w  w w .  ja  v  a2 s. co  m*/
 * @param target the original channel future.
 * @param bossGroup the boss group.
 * @param workerGroup the worker group.
 * @return the wrapped future.
 */
@NotNull
protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup,
        @NotNull final NioEventLoopGroup workerGroup) {
    return new ChannelFuture() {
        @Override
        public Channel channel() {
            return target.channel();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.addListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.addListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.removeListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.removeListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture sync() throws InterruptedException {
            ChannelFuture result = null;

            try {
                result = target.sync();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }

            return result;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture syncUninterruptibly() {
            return target.syncUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture await() throws InterruptedException {
            return target.await();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture awaitUninterruptibly() {
            return target.awaitUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isSuccess() {
            return target.isSuccess();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancellable() {
            return target.isCancellable();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Throwable cause() {
            return target.cause();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException {
            return target.await(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeoutMillis) throws InterruptedException {
            return target.await(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) {
            return target.awaitUninterruptibly(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeoutMillis) {
            return target.awaitUninterruptibly(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void getNow() {
            return target.getNow();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean cancel(final boolean mayInterruptIfRunning) {
            return target.cancel(mayInterruptIfRunning);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancelled() {
            return target.isCancelled();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isDone() {
            return target.isDone();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get() throws InterruptedException, ExecutionException {
            return target.get();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get(final long timeout, @NotNull final TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return target.get(timeout, unit);
        }
    };
}

From source file:org.apache.hive.spark.client.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *///  w w w. ja va 2  s.  co m
public static Promise<Rpc> createClient(Map<String, String> config, final NioEventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    final RpcConfiguration rpcConf = new RpcConfiguration(config);
    int connectTimeoutMs = (int) rpcConf.getConnectTimeoutMs();

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask, rpcConf.getServerConnectTimeoutMs(),
            TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(rpcConf, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(rpcConf, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*from ww  w  .  j  a v a  2 s.  c  o m*/
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerAcceptorModule.java

License:Open Source License

@Override
public java.lang.AutoCloseable createInstance() {
    final BGPPeerRegistry peerRegistry = getAcceptingPeerRegistryDependency();
    final ChannelFuture futureChannel = getAcceptingBgpDispatcherDependency().createServer(peerRegistry,
            getAddress());/*from  w  w  w . j  a va  2  s  .  co  m*/

    // Validate future success
    futureChannel.addListener(future -> {
        Preconditions.checkArgument(future.isSuccess(), "Unable to start bgp server on %s", getAddress(),
                future.cause());
        final Channel channel = futureChannel.channel();
        if (Epoll.isAvailable()) {
            BGPPeerAcceptorModule.this.listenerRegistration = peerRegistry
                    .registerPeerRegisterListener(new PeerRegistryListenerImpl(channel.config()));
        }
    });

    return () -> {
        // This closes the acceptor and no new bgp connections will be accepted
        // Connections already established will be preserved
        futureChannel.cancel(true);
        futureChannel.channel().close();
        if (BGPPeerAcceptorModule.this.listenerRegistration != null) {
            BGPPeerAcceptorModule.this.listenerRegistration.close();
        }
    };
}

From source file:org.opendaylight.controller.netconf.test.tool.NetconfDeviceSimulator.java

License:Open Source License

public List<Integer> start(final Main.Params params) {
    LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount,
            params.ssh ? "SSH" : "TCP", params.startingPort);

    final Map<ModuleBuilder, String> moduleBuilders = parseSchemasToModuleBuilders(params);

    final NetconfServerDispatcherImpl dispatcher = createDispatcher(moduleBuilders, params.exi,
            params.generateConfigsTimeout, Optional.fromNullable(params.notificationFile));

    int currentPort = params.startingPort;

    final List<Integer> openDevices = Lists.newArrayList();

    // Generate key to temp folder
    final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();

    for (int i = 0; i < params.deviceCount; i++) {
        if (currentPort > 65535) {
            LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
            break;
        }/*from  w  w  w  .ja v a  2s  .c  om*/
        final InetSocketAddress address = getAddress(currentPort);

        final ChannelFuture server;
        if (params.ssh) {
            final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
            final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());

            server = dispatcher.createLocalServer(tcpLocalAddress);
            try {
                final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup,
                        nioExecutor);
                sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
                sshWrappers.add(sshServer);
            } catch (final BindException e) {
                LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
                // Close local server and continue
                server.cancel(true);
                if (server.isDone()) {
                    server.channel().close();
                }
                continue;
            } catch (final IOException e) {
                LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
                break;
            } finally {
                currentPort++;
            }

            try {
                server.get();
            } catch (final InterruptedException e) {
                throw new RuntimeException(e);
            } catch (final ExecutionException e) {
                LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
                continue;
            }

            LOG.debug("Simulated SSH device started on {}", address);

        } else {
            server = dispatcher.createServer(address);
            currentPort++;

            try {
                server.get();
            } catch (final InterruptedException e) {
                throw new RuntimeException(e);
            } catch (final ExecutionException e) {
                LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
                continue;
            }

            LOG.debug("Simulated TCP device started on {}", address);
        }

        devicesChannels.add(server.channel());
        openDevices.add(currentPort - 1);
    }

    if (openDevices.size() == params.deviceCount) {
        LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort,
                currentPort - 1);
    } else if (openDevices.size() == 0) {
        LOG.warn("No simulated devices started.");
    } else {
        LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
    }

    return openDevices;
}

From source file:org.opendaylight.netconf.test.tool.NetconfDeviceSimulator.java

License:Open Source License

public List<Integer> start(final TesttoolParameters params) {
    LOG.info("Starting {}, {} simulated devices starting on port {}", params.deviceCount,
            params.ssh ? "SSH" : "TCP", params.startingPort);

    final SharedSchemaRepository schemaRepo = new SharedSchemaRepository("netconf-simulator");
    final Set<Capability> capabilities = parseSchemasToModuleCapabilities(params, schemaRepo);

    final NetconfServerDispatcherImpl dispatcher = createDispatcher(capabilities, params.exi,
            params.generateConfigsTimeout, Optional.fromNullable(params.notificationFile), params.mdSal,
            Optional.fromNullable(params.initialConfigXMLFile),
            new SchemaSourceProvider<YangTextSchemaSource>() {
                @Override/*from  ww  w  .  j  ava2 s.co  m*/
                public CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> getSource(
                        final SourceIdentifier sourceIdentifier) {
                    return schemaRepo.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
                }
            });

    int currentPort = params.startingPort;

    final List<Integer> openDevices = Lists.newArrayList();

    // Generate key to temp folder
    final PEMGeneratorHostKeyProvider keyPairProvider = getPemGeneratorHostKeyProvider();

    for (int i = 0; i < params.deviceCount; i++) {
        if (currentPort > 65535) {
            LOG.warn("Port cannot be greater than 65535, stopping further attempts.");
            break;
        }
        final InetSocketAddress address = getAddress(params.ip, currentPort);

        final ChannelFuture server;
        if (params.ssh) {
            final InetSocketAddress bindingAddress = InetSocketAddress.createUnresolved("0.0.0.0", currentPort);
            final LocalAddress tcpLocalAddress = new LocalAddress(address.toString());

            server = dispatcher.createLocalServer(tcpLocalAddress);
            try {
                final SshProxyServer sshServer = new SshProxyServer(minaTimerExecutor, nettyThreadgroup,
                        nioExecutor);
                sshServer.bind(getSshConfiguration(bindingAddress, tcpLocalAddress, keyPairProvider));
                sshWrappers.add(sshServer);
            } catch (final BindException e) {
                LOG.warn("Cannot start simulated device on {}, port already in use. Skipping.", address);
                // Close local server and continue
                server.cancel(true);
                if (server.isDone()) {
                    server.channel().close();
                }
                continue;
            } catch (final IOException e) {
                LOG.warn("Cannot start simulated device on {} due to IOException.", address, e);
                break;
            } finally {
                currentPort++;
            }

            try {
                server.get();
            } catch (final InterruptedException e) {
                throw new RuntimeException(e);
            } catch (final ExecutionException e) {
                LOG.warn("Cannot start ssh simulated device on {}, skipping", address, e);
                continue;
            }

            LOG.debug("Simulated SSH device started on {}", address);

        } else {
            server = dispatcher.createServer(address);
            currentPort++;

            try {
                server.get();
            } catch (final InterruptedException e) {
                throw new RuntimeException(e);
            } catch (final ExecutionException e) {
                LOG.warn("Cannot start tcp simulated device on {}, skipping", address, e);
                continue;
            }

            LOG.debug("Simulated TCP device started on {}", address);
        }

        devicesChannels.add(server.channel());
        openDevices.add(currentPort - 1);
    }

    if (openDevices.size() == params.deviceCount) {
        LOG.info("All simulated devices started successfully from port {} to {}", params.startingPort,
                currentPort - 1);
    } else if (openDevices.size() == 0) {
        LOG.warn("No simulated devices started.");
    } else {
        LOG.warn("Not all simulated devices started successfully. Started devices ar on ports {}", openDevices);
    }

    return openDevices;
}

From source file:org.redisson.command.CommandAsyncService.java

License:Apache License

protected <V, R> void async(final boolean readOnlyMode, final NodeSource source, final Codec codec,
        final RedisCommand<V> command, final Object[] params, final RPromise<R> mainPromise,
        final int attempt) {
    if (mainPromise.isCancelled()) {
        return;/*from   w  ww.  ja  v a  2  s . co  m*/
    }

    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown"));
        return;
    }

    final AsyncDetails<V, R> details = AsyncDetails.acquire();
    if (isRedissonReferenceSupportEnabled()) {
        try {
            for (int i = 0; i < params.length; i++) {
                RedissonReference reference = redisson != null
                        ? RedissonObjectFactory.toReference(redisson, params[i])
                        : RedissonObjectFactory.toReference(redissonReactive, params[i]);
                params[i] = reference == null ? params[i] : reference;
            }
        } catch (Exception e) {
            connectionManager.getShutdownLatch().release();
            mainPromise.tryFailure(e);
            return;
        }
    }

    final RFuture<RedisConnection> connectionFuture;
    if (readOnlyMode) {
        connectionFuture = connectionManager.connectionReadOp(source, command);
    } else {
        connectionFuture = connectionManager.connectionWriteOp(source, command);
    }

    final RPromise<R> attemptPromise = connectionManager.newPromise();
    details.init(connectionFuture, attemptPromise, readOnlyMode, source, codec, command, params, mainPromise,
            attempt);

    final TimerTask retryTimerTask = new TimerTask() {

        @Override
        public void run(Timeout t) throws Exception {
            if (details.getAttemptPromise().isDone()) {
                return;
            }

            if (details.getConnectionFuture().cancel(false)) {
                connectionManager.getShutdownLatch().release();
            } else {
                if (details.getConnectionFuture().isSuccess()) {
                    ChannelFuture writeFuture = details.getWriteFuture();
                    if (writeFuture != null && !writeFuture.cancel(false) && writeFuture.isSuccess()) {
                        return;
                    }
                }
            }

            if (details.getMainPromise().isCancelled()) {
                if (details.getAttemptPromise().cancel(false)) {
                    AsyncDetails.release(details);
                }
                return;
            }

            if (details.getAttempt() == connectionManager.getConfig().getRetryAttempts()) {
                if (details.getException() == null) {
                    details.setException(new RedisTimeoutException("Command execution timeout for command: "
                            + command + " with params: " + LogHelper.toString(details.getParams())));
                }
                details.getAttemptPromise().tryFailure(details.getException());
                return;
            }
            if (!details.getAttemptPromise().cancel(false)) {
                return;
            }

            int count = details.getAttempt() + 1;
            if (log.isDebugEnabled()) {
                log.debug("attempt {} for command {} and params {}", count, details.getCommand(),
                        Arrays.toString(details.getParams()));
            }
            async(details.isReadOnlyMode(), details.getSource(), details.getCodec(), details.getCommand(),
                    details.getParams(), details.getMainPromise(), count);
            AsyncDetails.release(details);
        }
    };

    Timeout timeout = connectionManager.newTimeout(retryTimerTask,
            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    details.setTimeout(timeout);

    connectionFuture.addListener(new FutureListener<RedisConnection>() {
        @Override
        public void operationComplete(Future<RedisConnection> connFuture) throws Exception {
            if (connFuture.isCancelled()) {
                return;
            }

            if (!connFuture.isSuccess()) {
                connectionManager.getShutdownLatch().release();
                details.setException(convertException(connectionFuture));
                return;
            }

            if (details.getAttemptPromise().isDone() || details.getMainPromise().isDone()) {
                releaseConnection(source, connectionFuture, details.isReadOnlyMode(),
                        details.getAttemptPromise(), details);
                return;
            }

            final RedisConnection connection = connFuture.getNow();
            if (details.getSource().getRedirect() == Redirect.ASK) {
                List<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(2);
                RPromise<Void> promise = connectionManager.newPromise();
                list.add(new CommandData<Void, Void>(promise, details.getCodec(), RedisCommands.ASKING,
                        new Object[] {}));
                list.add(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(),
                        details.getCommand(), details.getParams()));
                RPromise<Void> main = connectionManager.newPromise();
                ChannelFuture future = connection.send(new CommandsData(main, list));
                details.setWriteFuture(future);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("aquired connection for command {} and params {} from slot {} using node {}",
                            details.getCommand(), Arrays.toString(details.getParams()), details.getSource(),
                            connection.getRedisClient().getAddr());
                }
                ChannelFuture future = connection.send(new CommandData<V, R>(details.getAttemptPromise(),
                        details.getCodec(), details.getCommand(), details.getParams()));
                details.setWriteFuture(future);
            }

            details.getWriteFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    checkWriteFuture(details, connection);
                }
            });

            releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(),
                    details);
        }
    });

    attemptPromise.addListener(new FutureListener<R>() {
        @Override
        public void operationComplete(Future<R> future) throws Exception {
            checkAttemptFuture(source, details, future);
        }
    });
}

From source file:org.redisson.command.CommandBatchService.java

License:Apache License

private void execute(final Entry entry, final NodeSource source, final RPromise<Void> mainPromise,
        final AtomicInteger slots, final int attempt, final boolean noResult) {
    if (mainPromise.isCancelled()) {
        return;//from   ww w.j a  va 2s. c  om
    }

    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.tryFailure(new IllegalStateException("Redisson is shutdown"));
        return;
    }

    final RPromise<Void> attemptPromise = connectionManager.newPromise();

    final AsyncDetails details = new AsyncDetails();

    final RFuture<RedisConnection> connectionFuture;
    if (entry.isReadOnlyMode()) {
        connectionFuture = connectionManager.connectionReadOp(source, null);
    } else {
        connectionFuture = connectionManager.connectionWriteOp(source, null);
    }

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }

            if (connectionFuture.cancel(false)) {
                connectionManager.getShutdownLatch().release();
            } else {
                if (connectionFuture.isSuccess()) {
                    ChannelFuture writeFuture = details.getWriteFuture();
                    if (writeFuture != null && !writeFuture.cancel(false) && writeFuture.isSuccess()) {
                        return;
                    }
                }
            }

            if (mainPromise.isCancelled()) {
                attemptPromise.cancel(false);
                return;
            }

            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                if (details.getException() == null) {
                    details.setException(new RedisTimeoutException("Batch command execution timeout"));
                }
                attemptPromise.tryFailure(details.getException());
                return;
            }
            if (!attemptPromise.cancel(false)) {
                return;
            }

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

    Timeout timeout = connectionManager.newTimeout(retryTimerTask,
            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    details.setTimeout(timeout);

    connectionFuture.addListener(new FutureListener<RedisConnection>() {
        @Override
        public void operationComplete(Future<RedisConnection> connFuture) throws Exception {
            checkConnectionFuture(entry, source, mainPromise, attemptPromise, details, connectionFuture,
                    noResult);
        }
    });

    attemptPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            details.getTimeout().cancel();
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                entry.clearErrors();
                execute(entry, new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.MOVED), mainPromise, slots,
                        attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisAskException) {
                RedisAskException ex = (RedisAskException) future.cause();
                entry.clearErrors();
                execute(entry, new NodeSource(ex.getSlot(), ex.getAddr(), Redirect.ASK), mainPromise, slots,
                        attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisLoadingException) {
                entry.clearErrors();
                execute(entry, source, mainPromise, slots, attempt, noResult);
                return;
            }
            if (future.cause() instanceof RedisTryAgainException) {
                entry.clearErrors();
                connectionManager.newTimeout(new TimerTask() {
                    @Override
                    public void run(Timeout timeout) throws Exception {
                        execute(entry, source, mainPromise, slots, attempt, noResult);
                    }
                }, 1, TimeUnit.SECONDS);
                return;
            }

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

From source file:sailfish.remoting.channel.AbstractExchangeChannel.java

License:Apache License

private void waitWriteDone(ChannelFuture future, int timeout, RequestProtocol request, boolean needRemoveTrace)
        throws SailfishException {
    boolean done = future.awaitUninterruptibly(timeout);
    if (!done) {//from  w  w  w.ja v a 2  s .  c  o m
        // useless at most of time when do writeAndFlush(...) invoke
        future.cancel(true);
        if (needRemoveTrace) {
            getTracer().remove(request.packetId());
        }
        throw new SailfishException(ExceptionCode.WRITE_TIMEOUT,
                String.format("write to remote[%s] timeout, protocol[%s]", channel.remoteAddress(), request));
    }
    if (!future.isSuccess()) {
        if (needRemoveTrace) {
            getTracer().remove(request.packetId());
        }
        throw new SailfishException(ExceptionCode.CHANNEL_WRITE_FAIL,
                String.format("write to remote[%s] fail, protocol[%s]", channel.remoteAddress(), request),
                future.cause());
    }
}

From source file:se.sics.kompics.network.netty.ChannelManager.java

License:Open Source License

void clearConnections() {
    // clear these early to try avoid sending messages on them while closing
    tcpActiveChannels.clear();//from w w  w .j  a  v  a 2  s.  c  o  m
    udtActiveChannels.clear();

    List<ChannelFuture> futures = new LinkedList<ChannelFuture>();

    synchronized (this) {
        component.extLog.info("Closing all connections...");
        for (ChannelFuture f : udtIncompleteChannels.values()) {
            try {
                f.cancel(false);
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }
        for (ChannelFuture f : tcpIncompleteChannels.values()) {
            try {
                f.cancel(false);
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }

        for (SocketChannel c : tcpChannelsByRemote.values()) {
            try {
                futures.add(c.close());
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }

        tcpActiveChannels.clear(); // clear them again just to be sure
        tcpChannels.clear();
        tcpChannelsByRemote.clear();

        for (UdtChannel c : udtChannelsByRemote.values()) {
            try {
                futures.add(c.close());
            } catch (Exception ex) {
                component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
            }
        }

        udtActiveChannels.clear();
        udtChannels.clear();
        udtChannelsByRemote.clear();

        udtBoundPorts.clear();

        udtIncompleteChannels.clear();
        tcpIncompleteChannels.clear();
    }
    for (ChannelFuture cf : futures) {
        try {
            cf.syncUninterruptibly();
        } catch (Exception ex) {
            component.extLog.warn("Error during Netty shutdown. Messages might have been lost! \n {}", ex);
        }
    }
}