Search in sources :

Example 11 with Future

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

the class DefaultHttp2ConnectionTest method removeAllStreamsWhileIteratingActiveStreamsAndExceptionOccurs.

@Test
public void removeAllStreamsWhileIteratingActiveStreamsAndExceptionOccurs() throws InterruptedException, Http2Exception {
    final Endpoint<Http2RemoteFlowController> remote = client.remote();
    final Endpoint<Http2LocalFlowController> local = client.local();
    for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
        local.createStream(c, false);
        remote.createStream(s, false);
    }
    final Promise<Void> promise = group.next().newPromise();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        client.forEachActiveStream(new Http2StreamVisitor() {

            @Override
            public boolean visit(Http2Stream stream) throws Http2Exception {
                // This close call is basically a noop, because the following statement will throw an exception.
                client.close(promise);
                // Do an invalid operation while iterating.
                remote.createStream(3, false);
                return true;
            }
        });
    } catch (Http2Exception ignored) {
        client.close(promise).addListener(new FutureListener<Void>() {

            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                assertTrue(promise.isDone());
                latch.countDown();
            }
        });
    }
    assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) CountDownLatch(java.util.concurrent.CountDownLatch) Endpoint(io.netty.handler.codec.http2.Http2Connection.Endpoint) Future(io.netty.util.concurrent.Future) Test(org.junit.Test)

Example 12 with Future

use of io.netty.util.concurrent.Future 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 ScheduledFuture<?> 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) throws Exception {
            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 ScheduledFuture<?> 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) ScheduledFuture(java.util.concurrent.ScheduledFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelException(io.netty.channel.ChannelException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 13 with Future

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

the class DnsNameResolverTest method testResolve0.

private static Map<String, InetAddress> testResolve0(DnsNameResolver resolver, Set<String> excludedDomains) throws InterruptedException {
    assertThat(resolver.isRecursionDesired(), is(true));
    final Map<String, InetAddress> results = new HashMap<String, InetAddress>();
    final Map<String, Future<InetAddress>> futures = new LinkedHashMap<String, Future<InetAddress>>();
    for (String name : DOMAINS) {
        if (excludedDomains.contains(name)) {
            continue;
        }
        resolve(resolver, futures, name);
    }
    for (Entry<String, Future<InetAddress>> e : futures.entrySet()) {
        String unresolved = e.getKey();
        InetAddress resolved = e.getValue().sync().getNow();
        logger.info("{}: {}", unresolved, resolved.getHostAddress());
        assertThat(resolved.getHostName(), is(unresolved));
        boolean typeMatches = false;
        for (InternetProtocolFamily f : resolver.resolvedInternetProtocolFamiliesUnsafe()) {
            Class<?> resolvedType = resolved.getClass();
            if (f.addressType().isAssignableFrom(resolvedType)) {
                typeMatches = true;
            }
        }
        assertThat(typeMatches, is(true));
        results.put(resolved.getHostName(), resolved);
    }
    return results;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) Future(io.netty.util.concurrent.Future) InetAddress(java.net.InetAddress) LinkedHashMap(java.util.LinkedHashMap)

Example 14 with Future

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

the class DnsNameResolverTest method testQueryMx.

@Test
public void testQueryMx() throws Exception {
    DnsNameResolver resolver = newResolver().build();
    try {
        assertThat(resolver.isRecursionDesired(), is(true));
        Map<String, Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>> futures = new LinkedHashMap<String, Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>>();
        for (String name : DOMAINS) {
            if (EXCLUSIONS_QUERY_MX.contains(name)) {
                continue;
            }
            queryMx(resolver, futures, name);
        }
        for (Entry<String, Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>> e : futures.entrySet()) {
            String hostname = e.getKey();
            Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> f = e.getValue().awaitUninterruptibly();
            DnsResponse response = f.getNow().content();
            assertThat(response.code(), is(DnsResponseCode.NOERROR));
            final int answerCount = response.count(DnsSection.ANSWER);
            final List<DnsRecord> mxList = new ArrayList<DnsRecord>(answerCount);
            for (int i = 0; i < answerCount; i++) {
                final DnsRecord r = response.recordAt(DnsSection.ANSWER, i);
                if (r.type() == DnsRecordType.MX) {
                    mxList.add(r);
                }
            }
            assertThat(mxList.size(), is(greaterThan(0)));
            StringBuilder buf = new StringBuilder();
            for (DnsRecord r : mxList) {
                ByteBuf recordContent = ((ByteBufHolder) r).content();
                buf.append(StringUtil.NEWLINE);
                buf.append('\t');
                buf.append(r.name());
                buf.append(' ');
                buf.append(r.type().name());
                buf.append(' ');
                buf.append(recordContent.readUnsignedShort());
                buf.append(' ');
                buf.append(DnsNameResolverContext.decodeDomainName(recordContent));
            }
            logger.info("{} has the following MX records:{}", hostname, buf);
            response.release();
        }
    } finally {
        resolver.close();
    }
}
Also used : AddressedEnvelope(io.netty.channel.AddressedEnvelope) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) LinkedHashMap(java.util.LinkedHashMap) DnsResponse(io.netty.handler.codec.dns.DnsResponse) Future(io.netty.util.concurrent.Future) ByteBufHolder(io.netty.buffer.ByteBufHolder) DnsRecord(io.netty.handler.codec.dns.DnsRecord) Test(org.junit.Test)

Example 15 with Future

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

the class ReentrantChannelTest method testCloseInFlush.

@Test
public void testCloseInFlush() throws Exception {
    LocalAddress addr = new LocalAddress("testCloseInFlush");
    ServerBootstrap sb = getLocalServerBootstrap();
    sb.bind(addr).sync().channel();
    Bootstrap cb = getLocalClientBootstrap();
    setInterest(Event.WRITE, Event.FLUSH, Event.CLOSE, Event.EXCEPTION);
    Channel clientChannel = cb.connect(addr).sync().channel();
    clientChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            promise.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    ctx.channel().close();
                }
            });
            super.write(ctx, msg, promise);
            ctx.channel().flush();
        }
    });
    clientChannel.write(createTestBuf(2000)).sync();
    clientChannel.closeFuture().sync();
    assertLog("WRITE\nFLUSH\nCLOSE\n");
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Future(io.netty.util.concurrent.Future) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Test(org.junit.Test)

Aggregations

Future (io.netty.util.concurrent.Future)49 FutureListener (io.netty.util.concurrent.FutureListener)29 RFuture (org.redisson.api.RFuture)22 ChannelFuture (io.netty.channel.ChannelFuture)15 ChannelFutureListener (io.netty.channel.ChannelFutureListener)11 Channel (io.netty.channel.Channel)10 ArrayList (java.util.ArrayList)10 IOException (java.io.IOException)9 Timeout (io.netty.util.Timeout)8 TimerTask (io.netty.util.TimerTask)8 AtomicReference (java.util.concurrent.atomic.AtomicReference)8 ScheduledFuture (io.netty.util.concurrent.ScheduledFuture)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 RedisException (org.redisson.client.RedisException)7 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)6 Collection (java.util.Collection)6 Test (org.junit.Test)6 RedisConnection (org.redisson.client.RedisConnection)6 RedisConnectionException (org.redisson.client.RedisConnectionException)6