Search in sources :

Example 11 with FutureListener

use of io.netty.util.concurrent.FutureListener in project redisson by redisson.

the class ReplicatedConnectionManager method scheduleMasterChangeCheck.

private void scheduleMasterChangeCheck(final ReplicatedServersConfig cfg) {
    monitorFuture = GlobalEventExecutor.INSTANCE.schedule(new Runnable() {

        @Override
        public void run() {
            final URL master = currentMaster.get();
            log.debug("Current master: {}", master);
            final AtomicInteger count = new AtomicInteger(cfg.getNodeAddresses().size());
            for (final URL addr : cfg.getNodeAddresses()) {
                if (isShuttingDown()) {
                    return;
                }
                RFuture<RedisConnection> connectionFuture = connect(cfg, addr);
                connectionFuture.addListener(new FutureListener<RedisConnection>() {

                    @Override
                    public void operationComplete(Future<RedisConnection> future) throws Exception {
                        if (!future.isSuccess()) {
                            log.error(future.cause().getMessage(), future.cause());
                            if (count.decrementAndGet() == 0) {
                                scheduleMasterChangeCheck(cfg);
                            }
                            return;
                        }
                        if (isShuttingDown()) {
                            return;
                        }
                        RedisConnection connection = future.getNow();
                        RFuture<Map<String, String>> result = connection.async(RedisCommands.INFO_REPLICATION);
                        result.addListener(new FutureListener<Map<String, String>>() {

                            @Override
                            public void operationComplete(Future<Map<String, String>> future) throws Exception {
                                if (!future.isSuccess()) {
                                    log.error(future.cause().getMessage(), future.cause());
                                    if (count.decrementAndGet() == 0) {
                                        scheduleMasterChangeCheck(cfg);
                                    }
                                    return;
                                }
                                Role role = Role.valueOf(future.getNow().get(ROLE_KEY));
                                if (Role.master.equals(role)) {
                                    if (master.equals(addr)) {
                                        log.debug("Current master {} unchanged", master);
                                    } else if (currentMaster.compareAndSet(master, addr)) {
                                        log.info("Master has changed from {} to {}", master, addr);
                                        changeMaster(singleSlotRange.getStartSlot(), addr.getHost(), addr.getPort());
                                    }
                                }
                                if (count.decrementAndGet() == 0) {
                                    scheduleMasterChangeCheck(cfg);
                                }
                            }
                        });
                    }
                });
            }
        }
    }, cfg.getScanInterval(), TimeUnit.MILLISECONDS);
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) RFuture(org.redisson.api.RFuture) URL(java.net.URL) RedisException(org.redisson.client.RedisException) RedisConnectionException(org.redisson.client.RedisConnectionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) RedisConnection(org.redisson.client.RedisConnection)

Example 12 with FutureListener

use of io.netty.util.concurrent.FutureListener in project redisson by redisson.

the class RedisClient method resolveAddr.

public CompletableFuture<InetSocketAddress> resolveAddr() {
    if (resolvedAddrFuture.get() != null) {
        return resolvedAddrFuture.get();
    }
    CompletableFuture<InetSocketAddress> promise = new CompletableFuture<>();
    if (!resolvedAddrFuture.compareAndSet(null, promise)) {
        return resolvedAddrFuture.get();
    }
    byte[] addr = NetUtil.createByteArrayFromIpAddressString(uri.getHost());
    if (addr != null) {
        try {
            resolvedAddr = new InetSocketAddress(InetAddress.getByAddress(uri.getHost(), addr), uri.getPort());
        } catch (UnknownHostException e) {
        // skip
        }
        promise.complete(resolvedAddr);
        return promise;
    }
    AddressResolver<InetSocketAddress> resolver = (AddressResolver<InetSocketAddress>) bootstrap.config().resolver().getResolver(bootstrap.config().group().next());
    Future<InetSocketAddress> resolveFuture = resolver.resolve(InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort()));
    resolveFuture.addListener((FutureListener<InetSocketAddress>) future -> {
        if (!future.isSuccess()) {
            promise.completeExceptionally(future.cause());
            return;
        }
        InetSocketAddress resolved = future.getNow();
        byte[] addr1 = resolved.getAddress().getAddress();
        resolvedAddr = new InetSocketAddress(InetAddress.getByAddress(uri.getHost(), addr1), resolved.getPort());
        promise.complete(resolvedAddr);
    });
    return promise;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) RedisURI(org.redisson.misc.RedisURI) AtomicReference(java.util.concurrent.atomic.AtomicReference) EpollDatagramChannel(io.netty.channel.epoll.EpollDatagramChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) RFuture(org.redisson.api.RFuture) InetAddress(java.net.InetAddress) CompletableFutureWrapper(org.redisson.misc.CompletableFutureWrapper) io.netty.channel(io.netty.channel) RedisChannelInitializer(org.redisson.client.handler.RedisChannelInitializer) Type(org.redisson.client.handler.RedisChannelInitializer.Type) AddressResolver(io.netty.resolver.AddressResolver) ChannelGroup(io.netty.channel.group.ChannelGroup) FutureListener(io.netty.util.concurrent.FutureListener) java.util.concurrent(java.util.concurrent) NetUtil(io.netty.util.NetUtil) DnsServerAddressStreamProviders(io.netty.resolver.dns.DnsServerAddressStreamProviders) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) HashedWheelTimer(io.netty.util.HashedWheelTimer) Timer(io.netty.util.Timer) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Future(io.netty.util.concurrent.Future) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) AddressResolver(io.netty.resolver.AddressResolver) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress)

Example 13 with FutureListener

use of io.netty.util.concurrent.FutureListener in project redisson by redisson.

the class RedisExecutor method handleBlockingOperations.

private void handleBlockingOperations(CompletableFuture<R> attemptPromise, RedisConnection connection, Long popTimeout) {
    FutureListener<Void> listener = f -> {
        mainPromise.completeExceptionally(new RedissonShutdownException("Redisson is shutdown"));
    };
    Timeout scheduledFuture;
    if (popTimeout != 0) {
        // handling cases when connection has been lost
        scheduledFuture = connectionManager.newTimeout(timeout -> {
            if (attemptPromise.complete(null)) {
                connection.forceFastReconnectAsync();
            }
        }, popTimeout + 1, TimeUnit.SECONDS);
    } else {
        scheduledFuture = null;
    }
    mainPromise.whenComplete((res, e) -> {
        if (scheduledFuture != null) {
            scheduledFuture.cancel();
        }
        synchronized (listener) {
            connectionManager.getShutdownPromise().removeListener(listener);
        }
        // handling cancel operation for blocking commands
        if ((mainPromise.isCancelled() || e instanceof InterruptedException) && !attemptPromise.isDone()) {
            log.debug("Canceled blocking operation {} used {}", command, connection);
            connection.forceFastReconnectAsync().whenComplete((r, ex) -> {
                attemptPromise.cancel(true);
            });
            return;
        }
        if (e instanceof RedissonShutdownException) {
            attemptPromise.completeExceptionally(e);
        }
    });
    synchronized (listener) {
        if (!mainPromise.isDone()) {
            connectionManager.getShutdownPromise().addListener(listener);
        }
    }
}
Also used : Codec(org.redisson.client.codec.Codec) LoggerFactory(org.slf4j.LoggerFactory) RedisURI(org.redisson.misc.RedisURI) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) BaseCodec(org.redisson.client.codec.BaseCodec) NodeSource(org.redisson.connection.NodeSource) ByteBuf(io.netty.buffer.ByteBuf) ScanResult(org.redisson.ScanResult) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) FutureListener(io.netty.util.concurrent.FutureListener) CancellationException(java.util.concurrent.CancellationException) LRUCacheMap(org.redisson.cache.LRUCacheMap) ConnectionManager(org.redisson.connection.ConnectionManager) org.redisson.client(org.redisson.client) CommandData(org.redisson.client.protocol.CommandData) CompletionException(java.util.concurrent.CompletionException) Redirect(org.redisson.connection.NodeSource.Redirect) RedissonShutdownException(org.redisson.RedissonShutdownException) ChannelFuture(io.netty.channel.ChannelFuture) RedisCommands(org.redisson.client.protocol.RedisCommands) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) RedisCommand(org.redisson.client.protocol.RedisCommand) RedissonObjectBuilder(org.redisson.liveobject.core.RedissonObjectBuilder) CommandsData(org.redisson.client.protocol.CommandsData) LogHelper(org.redisson.misc.LogHelper) Timeout(io.netty.util.Timeout) RedissonShutdownException(org.redisson.RedissonShutdownException)

Example 14 with FutureListener

use of io.netty.util.concurrent.FutureListener in project redisson by redisson.

the class SentinelConnectionManager method performSentinelDNSCheck.

private void performSentinelDNSCheck(FutureListener<List<InetSocketAddress>> commonListener) {
    for (RedisURI host : sentinelHosts) {
        Future<List<InetSocketAddress>> allNodes = sentinelResolver.resolveAll(InetSocketAddress.createUnresolved(host.getHost(), host.getPort()));
        allNodes.addListener((FutureListener<List<InetSocketAddress>>) future -> {
            if (!future.isSuccess()) {
                log.error("Unable to resolve " + host.getHost(), future.cause());
                return;
            }
            future.getNow().stream().map(addr -> toURI(addr)).filter(uri -> !sentinels.containsKey(uri)).forEach(uri -> registerSentinel(uri, getConfig(), host.getHost()));
        });
        if (commonListener != null) {
            allNodes.addListener(commonListener);
        }
    }
}
Also used : AddressResolver(io.netty.resolver.AddressResolver) java.util(java.util) NodeType(org.redisson.api.NodeType) org.redisson.config(org.redisson.config) Logger(org.slf4j.Logger) FutureListener(io.netty.util.concurrent.FutureListener) StringCodec(org.redisson.client.codec.StringCodec) java.util.concurrent(java.util.concurrent) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) org.redisson.client(org.redisson.client) LoggerFactory(org.slf4j.LoggerFactory) NetUtil(io.netty.util.NetUtil) RedisURI(org.redisson.misc.RedisURI) StringUtil(io.netty.util.internal.StringUtil) InetSocketAddress(java.net.InetSocketAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) Collectors(java.util.stream.Collectors) RedisCommands(org.redisson.client.protocol.RedisCommands) RFuture(org.redisson.api.RFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RedisStrictCommand(org.redisson.client.protocol.RedisStrictCommand) FreezeReason(org.redisson.connection.ClientConnectionsEntry.FreezeReason) Future(io.netty.util.concurrent.Future) RedisURI(org.redisson.misc.RedisURI)

Example 15 with FutureListener

use of io.netty.util.concurrent.FutureListener in project netty by netty.

the class SslHandler method safeClose.

private void safeClose(final ChannelHandlerContext ctx, final ChannelFuture flushFuture, final ChannelPromise promise) {
    if (!ctx.channel().isActive()) {
        ctx.close(promise);
        return;
    }
    final Future<?> timeoutFuture;
    if (!flushFuture.isDone()) {
        long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
        if (closeNotifyTimeout > 0) {
            // Force-close the connection if close_notify is not fully sent in time.
            timeoutFuture = ctx.executor().schedule(new Runnable() {

                @Override
                public void run() {
                    // May be done in the meantime as cancel(...) is only best effort.
                    if (!flushFuture.isDone()) {
                        logger.warn("{} Last write attempt timed out; force-closing the connection.", ctx.channel());
                        addCloseListener(ctx.close(ctx.newPromise()), promise);
                    }
                }
            }, closeNotifyTimeout, TimeUnit.MILLISECONDS);
        } else {
            timeoutFuture = null;
        }
    } else {
        timeoutFuture = null;
    }
    // Close the connection if close_notify is sent in time.
    flushFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture f) {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
            final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
            if (closeNotifyReadTimeout <= 0) {
                // Trigger the close in all cases to make sure the promise is notified
                // See https://github.com/netty/netty/issues/2358
                addCloseListener(ctx.close(ctx.newPromise()), promise);
            } else {
                final Future<?> closeNotifyReadTimeoutFuture;
                if (!sslClosePromise.isDone()) {
                    closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() {

                        @Override
                        public void run() {
                            if (!sslClosePromise.isDone()) {
                                logger.debug("{} did not receive close_notify in {}ms; force-closing the connection.", ctx.channel(), closeNotifyReadTimeout);
                                // Do the close now...
                                addCloseListener(ctx.close(ctx.newPromise()), promise);
                            }
                        }
                    }, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
                } else {
                    closeNotifyReadTimeoutFuture = null;
                }
                // Do the close once the we received the close_notify.
                sslClosePromise.addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) throws Exception {
                        if (closeNotifyReadTimeoutFuture != null) {
                            closeNotifyReadTimeoutFuture.cancel(false);
                        }
                        addCloseListener(ctx.close(ctx.newPromise()), promise);
                    }
                });
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Aggregations

FutureListener (io.netty.util.concurrent.FutureListener)29 Future (io.netty.util.concurrent.Future)26 RFuture (org.redisson.api.RFuture)20 ChannelFuture (io.netty.channel.ChannelFuture)10 ChannelFutureListener (io.netty.channel.ChannelFutureListener)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 Timeout (io.netty.util.Timeout)6 TimerTask (io.netty.util.TimerTask)6 ArrayList (java.util.ArrayList)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 RedisConnection (org.redisson.client.RedisConnection)6 Channel (io.netty.channel.Channel)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)4 ScheduledFuture (io.netty.util.concurrent.ScheduledFuture)4 Test (org.junit.jupiter.api.Test)4 RedisConnectionException (org.redisson.client.RedisConnectionException)4 RedisException (org.redisson.client.RedisException)4 NodeSource (org.redisson.connection.NodeSource)4