use of io.netty.channel.socket.DatagramChannel in project camel by apache.
the class SingleUDPNettyServerBootstrapFactory method startServerBootstrap.
protected void startServerBootstrap() throws Exception {
// create non-shared worker pool
EventLoopGroup wg = configuration.getWorkerGroup();
if (wg == null) {
// create new pool which we should shutdown when stopping as its not shared
workerGroup = new NettyWorkerPoolBuilder().withNativeTransport(configuration.isNativeTransport()).withWorkerCount(configuration.getWorkerCount()).withName("NettyServerTCPWorker").build();
wg = workerGroup;
}
Bootstrap bootstrap = new Bootstrap();
if (configuration.isNativeTransport()) {
bootstrap.group(wg).channel(EpollDatagramChannel.class);
} else {
bootstrap.group(wg).channel(NioDatagramChannel.class);
}
// We cannot set the child option here
bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
// only set this if user has specified
if (configuration.getReceiveBufferSizePredictor() > 0) {
bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(configuration.getReceiveBufferSizePredictor()));
}
if (configuration.getBacklog() > 0) {
bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
}
Map<String, Object> options = configuration.getOptions();
if (options != null) {
for (Map.Entry<String, Object> entry : options.entrySet()) {
String value = entry.getValue().toString();
ChannelOption<Object> option = ChannelOption.valueOf(entry.getKey());
//TODO: find a way to add primitive Netty options without having to add them to the Camel registry.
if (EndpointHelper.isReferenceParameter(value)) {
String name = value.substring(1);
Object o = CamelContextHelper.mandatoryLookup(camelContext, name);
bootstrap.option(option, o);
} else {
bootstrap.option(option, value);
}
}
}
LOG.debug("Created Bootstrap {}", bootstrap);
// set the pipeline factory, which creates the pipeline for each newly created channels
bootstrap.handler(pipelineFactory);
InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);
if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
ChannelFuture channelFuture = bootstrap.bind(configuration.getPort()).sync();
channel = channelFuture.channel();
DatagramChannel datagramChannel = (DatagramChannel) channel;
String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE : configuration.getNetworkInterface();
multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
ObjectHelper.notNull(multicastNetworkInterface, "No network interface found for '" + networkInterface + "'.");
LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] { configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() });
datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
allChannels.add(datagramChannel);
} else {
LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
ChannelFuture channelFuture = bootstrap.bind(hostAddress).sync();
channel = channelFuture.channel();
allChannels.add(channel);
}
}
use of io.netty.channel.socket.DatagramChannel in project reactor-netty by reactor.
the class UdpServer method newHandler.
@Override
public Mono<? extends NettyContext> newHandler(BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>> handler) {
final BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>> targetHandler = null == handler ? ChannelOperations.noopHandler() : handler;
return Mono.create(sink -> {
Bootstrap b = options.get();
SocketAddress adr = options.getAddress();
if (adr == null) {
sink.error(new NullPointerException("Provided UdpServerOptions do not " + "define any address to bind to "));
return;
}
b.localAddress(adr);
ContextHandler<DatagramChannel> c = doHandler(targetHandler, sink, adr);
b.handler(c);
c.setFuture(b.bind());
});
}
use of io.netty.channel.socket.DatagramChannel in project netty by netty.
the class DnsNameResolverTest method testFollowNsRedirects.
private void testFollowNsRedirects(DnsCache cache, AuthoritativeDnsServerCache authoritativeDnsServerCache, final boolean invalidNsFirst) throws Exception {
final String domain = "netty.io";
final String ns1Name = "ns1." + domain;
final String ns2Name = "ns2." + domain;
final InetAddress expected = InetAddress.getByAddress("some.record." + domain, new byte[] { 10, 10, 10, 10 });
// This is used to simulate a query timeout...
final DatagramSocket socket = new DatagramSocket(new InetSocketAddress(0));
final TestDnsServer dnsServerAuthority = new TestDnsServer(new RecordStore() {
@Override
public Set<ResourceRecord> getRecords(QuestionRecord question) {
if (question.getDomainName().equals(expected.getHostName())) {
return Collections.singleton(newARecord(expected.getHostName(), expected.getHostAddress()));
}
return Collections.emptySet();
}
});
dnsServerAuthority.start();
TestDnsServer redirectServer = new TestDnsServer(new HashSet<String>(asList(expected.getHostName(), ns1Name, ns2Name))) {
@Override
protected DnsMessage filterMessage(DnsMessage message) {
for (QuestionRecord record : message.getQuestionRecords()) {
if (record.getDomainName().equals(expected.getHostName())) {
message.getAdditionalRecords().clear();
message.getAnswerRecords().clear();
if (invalidNsFirst) {
message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns2Name));
message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
} else {
message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns2Name));
}
return message;
}
}
return message;
}
};
redirectServer.start();
EventLoopGroup group = new NioEventLoopGroup(1);
final DnsNameResolver resolver = new DnsNameResolver(group.next(), 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
InetSocketAddress newRedirectServerAddress(InetAddress server) {
try {
if (server.getHostName().startsWith(ns1Name)) {
return new InetSocketAddress(InetAddress.getByAddress(ns1Name, dnsServerAuthority.localAddress().getAddress().getAddress()), dnsServerAuthority.localAddress().getPort());
}
if (server.getHostName().startsWith(ns2Name)) {
return new InetSocketAddress(InetAddress.getByAddress(ns2Name, NetUtil.LOCALHOST.getAddress()), socket.getLocalPort());
}
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
return super.newRedirectServerAddress(server);
}
};
try {
List<InetAddress> resolved = resolver.resolveAll(expected.getHostName()).syncUninterruptibly().getNow();
assertEquals(1, resolved.size());
assertEquals(expected, resolved.get(0));
List<InetAddress> resolved2 = resolver.resolveAll(expected.getHostName()).syncUninterruptibly().getNow();
assertEquals(1, resolved2.size());
assertEquals(expected, resolved2.get(0));
if (authoritativeDnsServerCache != NoopAuthoritativeDnsServerCache.INSTANCE) {
DnsServerAddressStream cached = authoritativeDnsServerCache.get(domain + '.');
assertEquals(2, cached.size());
InetSocketAddress ns1Address = InetSocketAddress.createUnresolved(ns1Name + '.', DefaultDnsServerAddressStreamProvider.DNS_PORT);
InetSocketAddress ns2Address = InetSocketAddress.createUnresolved(ns2Name + '.', DefaultDnsServerAddressStreamProvider.DNS_PORT);
if (invalidNsFirst) {
assertEquals(ns2Address, cached.next());
assertEquals(ns1Address, cached.next());
} else {
assertEquals(ns1Address, cached.next());
assertEquals(ns2Address, cached.next());
}
}
if (cache != NoopDnsCache.INSTANCE) {
List<? extends DnsCacheEntry> ns1Cached = cache.get(ns1Name + '.', null);
assertEquals(1, ns1Cached.size());
DnsCacheEntry nsEntry = ns1Cached.get(0);
assertNotNull(nsEntry.address());
assertNull(nsEntry.cause());
List<? extends DnsCacheEntry> ns2Cached = cache.get(ns2Name + '.', null);
if (invalidNsFirst) {
assertEquals(1, ns2Cached.size());
DnsCacheEntry ns2Entry = ns2Cached.get(0);
assertNotNull(ns2Entry.address());
assertNull(ns2Entry.cause());
} else {
// We should not even have tried to resolve the DNS name so this should be null.
assertNull(ns2Cached);
}
List<? extends DnsCacheEntry> expectedCached = cache.get(expected.getHostName(), null);
assertEquals(1, expectedCached.size());
DnsCacheEntry expectedEntry = expectedCached.get(0);
assertEquals(expected, expectedEntry.address());
assertNull(expectedEntry.cause());
}
} finally {
resolver.close();
group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
redirectServer.stop();
dnsServerAuthority.stop();
socket.close();
}
}
use of io.netty.channel.socket.DatagramChannel 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();
}
}
use of io.netty.channel.socket.DatagramChannel in project netty by netty.
the class DnsNameResolverTest method testRecursiveResolveCache.
private static void testRecursiveResolveCache(boolean cache) throws Exception {
final String hostname = "some.record.netty.io";
final String hostname2 = "some2.record.netty.io";
final TestDnsServer dnsServerAuthority = new TestDnsServer(new HashSet<String>(asList(hostname, hostname2)));
dnsServerAuthority.start();
TestDnsServer dnsServer = new RedirectingTestDnsServer(hostname, dnsServerAuthority.localAddress().getAddress().getHostAddress());
dnsServer.start();
TestAuthoritativeDnsServerCache nsCache = new TestAuthoritativeDnsServerCache(cache ? new DefaultAuthoritativeDnsServerCache() : NoopAuthoritativeDnsServerCache.INSTANCE);
TestRecursiveCacheDnsQueryLifecycleObserverFactory lifecycleObserverFactory = new TestRecursiveCacheDnsQueryLifecycleObserverFactory();
EventLoopGroup group = new NioEventLoopGroup(1);
final DnsNameResolver resolver = new DnsNameResolver(group.next(), new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class), NoopDnsCache.INSTANCE, nsCache, lifecycleObserverFactory, 3000, ResolvedAddressTypes.IPV4_ONLY, true, 10, true, 4096, false, HostsFileEntriesResolver.DEFAULT, new SingletonDnsServerAddressStreamProvider(dnsServer.localAddress()), DnsNameResolver.DEFAULT_SEARCH_DOMAINS, 0, true) {
@Override
InetSocketAddress newRedirectServerAddress(InetAddress server) {
if (server.equals(dnsServerAuthority.localAddress().getAddress())) {
return new InetSocketAddress(server, dnsServerAuthority.localAddress().getPort());
}
return super.newRedirectServerAddress(server);
}
};
// Java7 will strip of the "." so we need to adjust the expected dnsname. Both are valid in terms of the RFC
// so its ok.
String expectedDnsName = PlatformDependent.javaVersion() == 7 ? "dns4.some.record.netty.io" : "dns4.some.record.netty.io.";
try {
resolver.resolveAll(hostname).syncUninterruptibly();
TestDnsQueryLifecycleObserver observer = lifecycleObserverFactory.observers.poll();
assertNotNull(observer);
assertTrue(lifecycleObserverFactory.observers.isEmpty());
assertEquals(4, observer.events.size());
QueryWrittenEvent writtenEvent1 = (QueryWrittenEvent) observer.events.poll();
assertEquals(dnsServer.localAddress(), writtenEvent1.dnsServerAddress);
QueryRedirectedEvent redirectedEvent = (QueryRedirectedEvent) observer.events.poll();
assertEquals(expectedDnsName, redirectedEvent.nameServers.get(0).getHostName());
assertEquals(dnsServerAuthority.localAddress(), redirectedEvent.nameServers.get(0));
QueryWrittenEvent writtenEvent2 = (QueryWrittenEvent) observer.events.poll();
assertEquals(dnsServerAuthority.localAddress(), writtenEvent2.dnsServerAddress);
QuerySucceededEvent succeededEvent = (QuerySucceededEvent) observer.events.poll();
if (cache) {
assertNull(nsCache.cache.get("io."));
assertNull(nsCache.cache.get("netty.io."));
DnsServerAddressStream entries = nsCache.cache.get("record.netty.io.");
// First address should be resolved (as we received a matching additional record), second is unresolved.
assertEquals(2, entries.size());
assertFalse(entries.next().isUnresolved());
assertTrue(entries.next().isUnresolved());
assertNull(nsCache.cache.get(hostname));
// Test again via cache.
resolver.resolveAll(hostname).syncUninterruptibly();
observer = lifecycleObserverFactory.observers.poll();
assertNotNull(observer);
assertTrue(lifecycleObserverFactory.observers.isEmpty());
assertEquals(2, observer.events.size());
writtenEvent1 = (QueryWrittenEvent) observer.events.poll();
assertEquals(expectedDnsName, writtenEvent1.dnsServerAddress.getHostName());
assertEquals(dnsServerAuthority.localAddress(), writtenEvent1.dnsServerAddress);
succeededEvent = (QuerySucceededEvent) observer.events.poll();
resolver.resolveAll(hostname2).syncUninterruptibly();
observer = lifecycleObserverFactory.observers.poll();
assertNotNull(observer);
assertTrue(lifecycleObserverFactory.observers.isEmpty());
assertEquals(2, observer.events.size());
writtenEvent1 = (QueryWrittenEvent) observer.events.poll();
assertEquals(expectedDnsName, writtenEvent1.dnsServerAddress.getHostName());
assertEquals(dnsServerAuthority.localAddress(), writtenEvent1.dnsServerAddress);
succeededEvent = (QuerySucceededEvent) observer.events.poll();
// Check that it only queried the cache for record.netty.io.
assertNull(nsCache.cacheHits.get("io."));
assertNull(nsCache.cacheHits.get("netty.io."));
assertNotNull(nsCache.cacheHits.get("record.netty.io."));
assertNull(nsCache.cacheHits.get("some.record.netty.io."));
}
} finally {
resolver.close();
group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
dnsServer.stop();
dnsServerAuthority.stop();
}
}
Aggregations