Search in sources :

Example 16 with EventLoop

use of io.netty.channel.EventLoop in project netty by netty.

the class AbstractEpollChannel method clearEpollIn.

final void clearEpollIn() {
    // Only clear if registered with an EventLoop as otherwise
    if (isRegistered()) {
        final EventLoop loop = eventLoop();
        final AbstractEpollUnsafe unsafe = (AbstractEpollUnsafe) unsafe();
        if (loop.inEventLoop()) {
            unsafe.clearEpollIn0();
        } else {
            // schedule a task to clear the EPOLLIN as it is not safe to modify it directly
            loop.execute(new Runnable() {

                @Override
                public void run() {
                    if (!unsafe.readPending && !config().isAutoRead()) {
                        // Still no read triggered so clear it now
                        unsafe.clearEpollIn0();
                    }
                }
            });
        }
    } else {
        // The EventLoop is not registered atm so just update the flags so the correct value
        // will be used once the channel is registered
        flags &= ~Native.EPOLLIN;
    }
}
Also used : EventLoop(io.netty.channel.EventLoop)

Example 17 with EventLoop

use of io.netty.channel.EventLoop in project netty by netty.

the class DnsNameResolverTest method testNSRecordsFromCache.

@Test
public void testNSRecordsFromCache() throws Exception {
    final String domain = "netty.io";
    final String hostname = "test.netty.io";
    final String ns0Name = "ns0." + domain + '.';
    final String ns1Name = "ns1." + domain + '.';
    final String ns2Name = "ns2." + domain + '.';
    final InetSocketAddress ns0Address = new InetSocketAddress(InetAddress.getByAddress(ns0Name, new byte[] { 10, 1, 0, 1 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns1Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 1 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns2Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 2 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns3Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 3 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns4Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 4 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns5Address = new InetSocketAddress(InetAddress.getByAddress(ns2Name, new byte[] { 10, 0, 0, 5 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    TestDnsServer redirectServer = new TestDnsServer(new HashSet<String>(asList(hostname, ns1Name))) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            for (QuestionRecord record : message.getQuestionRecords()) {
                if (record.getDomainName().equals(hostname)) {
                    message.getAdditionalRecords().clear();
                    message.getAnswerRecords().clear();
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns0Name));
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns2Name));
                    message.getAdditionalRecords().add(newARecord(ns0Address));
                    message.getAdditionalRecords().add(newARecord(ns5Address));
                    return message;
                }
            }
            return message;
        }

        private ResourceRecord newARecord(InetSocketAddress address) {
            return newARecord(address.getHostName(), address.getAddress().getHostAddress());
        }
    };
    redirectServer.start();
    EventLoopGroup group = new NioEventLoopGroup(1);
    final List<InetSocketAddress> cached = new CopyOnWriteArrayList<InetSocketAddress>();
    final AuthoritativeDnsServerCache authoritativeDnsServerCache = new AuthoritativeDnsServerCache() {

        @Override
        public DnsServerAddressStream get(String hostname) {
            return null;
        }

        @Override
        public void cache(String hostname, InetSocketAddress address, long originalTtl, EventLoop loop) {
            cached.add(address);
        }

        @Override
        public void clear() {
        // NOOP
        }

        @Override
        public boolean clear(String hostname) {
            return false;
        }
    };
    EventLoop loop = group.next();
    DefaultDnsCache cache = new DefaultDnsCache();
    cache.cache(ns1Name, null, ns1Address.getAddress(), 10000, loop);
    cache.cache(ns1Name, null, ns2Address.getAddress(), 10000, loop);
    cache.cache(ns1Name, null, ns3Address.getAddress(), 10000, loop);
    cache.cache(ns1Name, null, ns4Address.getAddress(), 10000, loop);
    final AtomicReference<DnsServerAddressStream> redirectedRef = new AtomicReference<DnsServerAddressStream>();
    final DnsNameResolver resolver = new DnsNameResolver(loop, new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class), cache, authoritativeDnsServerCache, NoopDnsQueryLifecycleObserverFactory.INSTANCE, 2000, ResolvedAddressTypes.IPV4_ONLY, true, 10, true, 4096, false, HostsFileEntriesResolver.DEFAULT, new SingletonDnsServerAddressStreamProvider(redirectServer.localAddress()), DnsNameResolver.DEFAULT_SEARCH_DOMAINS, 0, true) {

        @Override
        protected DnsServerAddressStream newRedirectDnsServerStream(String hostname, List<InetSocketAddress> nameservers) {
            DnsServerAddressStream stream = new SequentialDnsServerAddressStream(nameservers, 0);
            redirectedRef.set(stream);
            return stream;
        }
    };
    try {
        Throwable cause = resolver.resolveAll(hostname).await().cause();
        assertTrue(cause instanceof UnknownHostException);
        DnsServerAddressStream redirected = redirectedRef.get();
        assertNotNull(redirected);
        assertEquals(6, redirected.size());
        assertEquals(3, cached.size());
        // The redirected addresses should have been retrieven from the DnsCache if not resolved, so these are
        // fully resolved.
        assertEquals(ns0Address, redirected.next());
        assertEquals(ns1Address, redirected.next());
        assertEquals(ns2Address, redirected.next());
        assertEquals(ns3Address, redirected.next());
        assertEquals(ns4Address, redirected.next());
        assertEquals(ns5Address, redirected.next());
        // As this address was supplied as ADDITIONAL we should put it resolved into the cache.
        assertEquals(ns0Address, cached.get(0));
        assertEquals(ns5Address, cached.get(1));
        // We should have put the unresolved address in the AuthoritativeDnsServerCache (but only 1 time)
        assertEquals(unresolved(ns1Address), cached.get(2));
    } finally {
        resolver.close();
        group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        redirectServer.stop();
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) Collections.singletonList(java.util.Collections.singletonList) Arrays.asList(java.util.Arrays.asList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) UnknownHostException(java.net.UnknownHostException) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) EventLoop(io.netty.channel.EventLoop) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.jupiter.api.Test)

Example 18 with EventLoop

use of io.netty.channel.EventLoop in project netty by netty.

the class DnsNameResolverTest method testCNameCached.

@Test
public void testCNameCached() throws Exception {
    final Map<String, String> cache = new ConcurrentHashMap<String, String>();
    final AtomicInteger cnameQueries = new AtomicInteger();
    final AtomicInteger aQueries = new AtomicInteger();
    TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() {

        @Override
        public Set<ResourceRecord> getRecords(QuestionRecord question) {
            if ("cname.netty.io".equals(question.getDomainName())) {
                aQueries.incrementAndGet();
                return Collections.<ResourceRecord>singleton(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.A, Collections.<String, Object>singletonMap(DnsAttribute.IP_ADDRESS.toLowerCase(), "10.0.0.99")));
            }
            if ("x.netty.io".equals(question.getDomainName())) {
                cnameQueries.incrementAndGet();
                return Collections.<ResourceRecord>singleton(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.CNAME, Collections.<String, Object>singletonMap(DnsAttribute.DOMAIN_NAME.toLowerCase(), "cname.netty.io")));
            }
            if ("y.netty.io".equals(question.getDomainName())) {
                cnameQueries.incrementAndGet();
                return Collections.<ResourceRecord>singleton(new TestDnsServer.TestResourceRecord(question.getDomainName(), RecordType.CNAME, Collections.<String, Object>singletonMap(DnsAttribute.DOMAIN_NAME.toLowerCase(), "x.netty.io")));
            }
            return Collections.emptySet();
        }
    });
    dnsServer2.start();
    DnsNameResolver resolver = null;
    try {
        DnsNameResolverBuilder builder = newResolver().recursionDesired(true).resolvedAddressTypes(ResolvedAddressTypes.IPV4_ONLY).maxQueriesPerResolve(16).nameServerProvider(new SingletonDnsServerAddressStreamProvider(dnsServer2.localAddress())).resolveCache(NoopDnsCache.INSTANCE).cnameCache(new DnsCnameCache() {

            @Override
            public String get(String hostname) {
                assertTrue(hostname.endsWith("."), hostname);
                return cache.get(hostname);
            }

            @Override
            public void cache(String hostname, String cname, long originalTtl, EventLoop loop) {
                assertTrue(hostname.endsWith("."), hostname);
                cache.put(hostname, cname);
            }

            @Override
            public void clear() {
            // NOOP
            }

            @Override
            public boolean clear(String hostname) {
                return false;
            }
        });
        resolver = builder.build();
        List<InetAddress> resolvedAddresses = resolver.resolveAll("x.netty.io").syncUninterruptibly().getNow();
        assertEquals(1, resolvedAddresses.size());
        assertTrue(resolvedAddresses.contains(InetAddress.getByAddress(new byte[] { 10, 0, 0, 99 })));
        assertEquals("cname.netty.io.", cache.get("x.netty.io."));
        assertEquals(1, cnameQueries.get());
        assertEquals(1, aQueries.get());
        resolvedAddresses = resolver.resolveAll("x.netty.io").syncUninterruptibly().getNow();
        assertEquals(1, resolvedAddresses.size());
        assertTrue(resolvedAddresses.contains(InetAddress.getByAddress(new byte[] { 10, 0, 0, 99 })));
        // Should not have queried for the CNAME again.
        assertEquals(1, cnameQueries.get());
        assertEquals(2, aQueries.get());
        resolvedAddresses = resolver.resolveAll("y.netty.io").syncUninterruptibly().getNow();
        assertEquals(1, resolvedAddresses.size());
        assertTrue(resolvedAddresses.contains(InetAddress.getByAddress(new byte[] { 10, 0, 0, 99 })));
        assertEquals("x.netty.io.", cache.get("y.netty.io."));
        // Will only query for one CNAME
        assertEquals(2, cnameQueries.get());
        assertEquals(3, aQueries.get());
        resolvedAddresses = resolver.resolveAll("y.netty.io").syncUninterruptibly().getNow();
        assertEquals(1, resolvedAddresses.size());
        assertTrue(resolvedAddresses.contains(InetAddress.getByAddress(new byte[] { 10, 0, 0, 99 })));
        // Should not have queried for the CNAME again.
        assertEquals(2, cnameQueries.get());
        assertEquals(4, aQueries.get());
    } finally {
        dnsServer2.stop();
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) EventLoop(io.netty.channel.EventLoop) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RecordStore(org.apache.directory.server.dns.store.RecordStore) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) InetAddress(java.net.InetAddress) Test(org.junit.jupiter.api.Test)

Example 19 with EventLoop

use of io.netty.channel.EventLoop in project netty by netty.

the class DnsNameResolverTest method testCancelPromise.

@Test
public void testCancelPromise() throws Exception {
    final EventLoop eventLoop = group.next();
    final Promise<InetAddress> promise = eventLoop.newPromise();
    final TestDnsServer dnsServer1 = new TestDnsServer(Collections.<String>emptySet()) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            promise.cancel(true);
            return message;
        }
    };
    dnsServer1.start();
    final AtomicBoolean isQuerySentToSecondServer = new AtomicBoolean();
    final TestDnsServer dnsServer2 = new TestDnsServer(Collections.<String>emptySet()) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            isQuerySentToSecondServer.set(true);
            return message;
        }
    };
    dnsServer2.start();
    DnsServerAddressStreamProvider nameServerProvider = new SequentialDnsServerAddressStreamProvider(dnsServer1.localAddress(), dnsServer2.localAddress());
    final DnsNameResolver resolver = new DnsNameResolverBuilder(group.next()).dnsQueryLifecycleObserverFactory(new TestRecursiveCacheDnsQueryLifecycleObserverFactory()).channelType(NioDatagramChannel.class).optResourceEnabled(false).nameServerProvider(nameServerProvider).build();
    try {
        resolver.resolve("non-existent.netty.io", promise).sync();
        fail();
    } catch (Exception e) {
        assertThat(e, is(instanceOf(CancellationException.class)));
    }
    assertThat(isQuerySentToSecondServer.get(), is(false));
}
Also used : NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) CancellationException(java.util.concurrent.CancellationException) DnsException(org.apache.directory.server.dns.DnsException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) BindException(java.net.BindException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EventLoop(io.netty.channel.EventLoop) CancellationException(java.util.concurrent.CancellationException) InetAddress(java.net.InetAddress) Test(org.junit.jupiter.api.Test)

Example 20 with EventLoop

use of io.netty.channel.EventLoop in project netty by netty.

the class DefaultAuthoritativeDnsServerCacheTest method testExpireWithTTL0.

private static void testExpireWithTTL0(int days) {
    EventLoopGroup group = new NioEventLoopGroup(1);
    try {
        EventLoop loop = group.next();
        final DefaultAuthoritativeDnsServerCache cache = new DefaultAuthoritativeDnsServerCache();
        cache.cache("netty.io", new InetSocketAddress(NetUtil.LOCALHOST, 53), days, loop);
    } finally {
        group.shutdownGracefully();
    }
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoop(io.netty.channel.EventLoop) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

EventLoop (io.netty.channel.EventLoop)79 EventLoopGroup (io.netty.channel.EventLoopGroup)27 Test (org.junit.jupiter.api.Test)27 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)18 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)17 Bootstrap (io.netty.bootstrap.Bootstrap)11 Channel (io.netty.channel.Channel)11 InetSocketAddress (java.net.InetSocketAddress)11 InetAddress (java.net.InetAddress)9 ChannelFuture (io.netty.channel.ChannelFuture)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 ChannelPromise (io.netty.channel.ChannelPromise)6 ChannelFutureListener (io.netty.channel.ChannelFutureListener)5 LocalAddress (io.netty.channel.local.LocalAddress)5 ClosedChannelException (java.nio.channels.ClosedChannelException)5 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)4 ChannelPipeline (io.netty.channel.ChannelPipeline)4 List (java.util.List)4 SingleThreadEventLoop (io.netty.channel.SingleThreadEventLoop)3 IOException (java.io.IOException)3