kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 06b8ec2621113ae0f2c0e241e048fb36ec0d408da9a52910a80e73ccb8e0071f |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-04-06 17:58 +02:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-04-06 17:58 +02:00 |
| Parents | dce1743c6d60, 7775fbd33656 |
7 files changed
modified driver-core/pom.xml +3 −0
| @@ -189,6 +189,9 @@ | ||
| 189 | 189 | <includes> |
| 190 | 190 | <include>io.netty:*</include> |
| 191 | 191 | </includes> |
| 192 | + <excludes> | |
| 193 | + <exclude>io.netty:netty-transport-native-epoll</exclude> | |
| 194 | + </excludes> | |
| 192 | 195 | </artifactSet> |
| 193 | 196 | <relocations> |
| 194 | 197 | <relocation> |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +18 −1
| @@ -581,6 +581,8 @@ | ||
| 581 | 581 | private SocketOptions socketOptions; |
| 582 | 582 | private QueryOptions queryOptions; |
| 583 | 583 | |
| 584 | + private NettyOptions nettyOptions = NettyOptions.DEFAULT_INSTANCE; | |
| 585 | + | |
| 584 | 586 | private Collection<Host.StateListener> listeners; |
| 585 | 587 | |
| 586 | 588 | |
| @@ -1038,6 +1040,20 @@ | ||
| 1038 | 1040 | return this; |
| 1039 | 1041 | } |
| 1040 | 1042 | |
| 1043 | + /** | |
| 1044 | + * Set the {@link NettyOptions} to use for the newly created Cluster. | |
| 1045 | + * <p> | |
| 1046 | + * If no Netty options are set through this method, {@link NettyOptions#DEFAULT_INSTANCE} | |
| 1047 | + * will be used as a default value, which means that no customization will be applied. | |
| 1048 | + * | |
| 1049 | + * @param nettyOptions the {@link NettyOptions} to use. | |
| 1050 | + * @return this builder. | |
| 1051 | + */ | |
| 1052 | + public Builder withNettyOptions(NettyOptions nettyOptions) { | |
| 1053 | + this.nettyOptions = nettyOptions; | |
| 1054 | + return this; | |
| 1055 | + } | |
| 1056 | + | |
| 1041 | 1057 | /** |
| 1042 | 1058 | * The configuration that will be used for the new cluster. |
| 1043 | 1059 | * <p> |
| @@ -1060,7 +1076,8 @@ | ||
| 1060 | 1076 | poolingOptions == null ? new PoolingOptions() : poolingOptions, |
| 1061 | 1077 | socketOptions == null ? new SocketOptions() : socketOptions, |
| 1062 | 1078 | metricsEnabled ? new MetricsOptions(jmxEnabled) : null, |
| 1063 | - queryOptions == null ? new QueryOptions() : queryOptions); | |
| 1079 | + queryOptions == null ? new QueryOptions() : queryOptions, | |
| 1080 | + nettyOptions); | |
| 1064 | 1081 | } |
| 1065 | 1082 | |
| 1066 | 1083 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +16 −2
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | * <li>low-level TCP configuration options (tcpNoDelay, keepAlive, ...).</li> |
| 27 | 27 | * <li>Metrics related options.</li> |
| 28 | 28 | * <li>Query related options (default consistency level, fetchSize, ...).</li> |
| 29 | + * <li>Netty layer customization options.</li> | |
| 29 | 30 | * </ul> |
| 30 | 31 | * This is also where you get the configured policies, though those cannot be changed |
| 31 | 32 | * (they are set during the built of the Cluster object). |
| @@ -39,6 +40,7 @@ | ||
| 39 | 40 | private final SocketOptions socketOptions; |
| 40 | 41 | private final MetricsOptions metricsOptions; |
| 41 | 42 | private final QueryOptions queryOptions; |
| 43 | + private final NettyOptions nettyOptions; | |
| 42 | 44 | |
| 43 | 45 | /* |
| 44 | 46 | * Creates a configuration object. |
| @@ -49,7 +51,8 @@ | ||
| 49 | 51 | new PoolingOptions(), |
| 50 | 52 | new SocketOptions(), |
| 51 | 53 | new MetricsOptions(), |
| 52 | - new QueryOptions()); | |
| 54 | + new QueryOptions(), | |
| 55 | + NettyOptions.DEFAULT_INSTANCE); | |
| 53 | 56 | } |
| 54 | 57 | |
| 55 | 58 | /** |
| @@ -61,19 +64,22 @@ | ||
| 61 | 64 | * @param socketOptions the socket options to use |
| 62 | 65 | * @param metricsOptions the metrics options, or null to disable metrics. |
| 63 | 66 | * @param queryOptions defaults related to queries. |
| 67 | + * @param nettyOptions the {@link NettyOptions} instance to use | |
| 64 | 68 | */ |
| 65 | 69 | public Configuration(Policies policies, |
| 66 | 70 | ProtocolOptions protocolOptions, |
| 67 | 71 | PoolingOptions poolingOptions, |
| 68 | 72 | SocketOptions socketOptions, |
| 69 | 73 | MetricsOptions metricsOptions, |
| 70 | - QueryOptions queryOptions) { | |
| 74 | + QueryOptions queryOptions, | |
| 75 | + NettyOptions nettyOptions) { | |
| 71 | 76 | this.policies = policies; |
| 72 | 77 | this.protocolOptions = protocolOptions; |
| 73 | 78 | this.poolingOptions = poolingOptions; |
| 74 | 79 | this.socketOptions = socketOptions; |
| 75 | 80 | this.metricsOptions = metricsOptions; |
| 76 | 81 | this.queryOptions = queryOptions; |
| 82 | + this.nettyOptions = nettyOptions; | |
| 77 | 83 | } |
| 78 | 84 | |
| 79 | 85 | void register(Cluster.Manager manager) { |
| @@ -138,4 +144,12 @@ | ||
| 138 | 144 | public QueryOptions getQueryOptions() { |
| 139 | 145 | return queryOptions; |
| 140 | 146 | } |
| 147 | + | |
| 148 | + /** | |
| 149 | + * Returns the {@link NettyOptions} instance for this configuration. | |
| 150 | + * @return the {@link NettyOptions} instance for this configuration. | |
| 151 | + */ | |
| 152 | + public NettyOptions getNettyOptions() { | |
| 153 | + return nettyOptions; | |
| 154 | + } | |
| 141 | 155 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +20 −65
| @@ -15,9 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.lang.reflect.Constructor; | |
| 19 | 18 | import java.net.InetSocketAddress; |
| 20 | -import java.util.*; | |
| 19 | +import java.util.HashSet; | |
| 20 | +import java.util.Iterator; | |
| 21 | +import java.util.List; | |
| 22 | +import java.util.Queue; | |
| 21 | 23 | import java.util.concurrent.*; |
| 22 | 24 | import java.util.concurrent.atomic.AtomicBoolean; |
| 23 | 25 | import java.util.concurrent.atomic.AtomicInteger; |
| @@ -25,17 +27,12 @@ | ||
| 25 | 27 | |
| 26 | 28 | import com.google.common.collect.Lists; |
| 27 | 29 | import com.google.common.util.concurrent.AbstractFuture; |
| 28 | -import com.google.common.util.concurrent.ThreadFactoryBuilder; | |
| 29 | 30 | import com.google.common.util.concurrent.Uninterruptibles; |
| 30 | 31 | import io.netty.bootstrap.Bootstrap; |
| 31 | 32 | import io.netty.channel.*; |
| 32 | -import io.netty.channel.epoll.EpollEventLoopGroup; | |
| 33 | -import io.netty.channel.epoll.EpollSocketChannel; | |
| 34 | 33 | import io.netty.channel.group.ChannelGroup; |
| 35 | 34 | import io.netty.channel.group.DefaultChannelGroup; |
| 36 | -import io.netty.channel.nio.NioEventLoopGroup; | |
| 37 | 35 | import io.netty.channel.socket.SocketChannel; |
| 38 | -import io.netty.channel.socket.nio.NioSocketChannel; | |
| 39 | 36 | import io.netty.handler.ssl.SslHandler; |
| 40 | 37 | import io.netty.handler.timeout.IdleStateEvent; |
| 41 | 38 | import io.netty.handler.timeout.IdleStateHandler; |
| @@ -65,7 +62,6 @@ | ||
| 65 | 62 | private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; |
| 66 | 63 | |
| 67 | 64 | private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false); |
| 68 | - private static final boolean FORCE_NIO = SystemProperties.getBoolean("com.datastax.driver.FORCE_NIO", false); | |
| 69 | 65 | |
| 70 | 66 | public final InetSocketAddress address; |
| 71 | 67 | private final String name; |
| @@ -105,7 +101,8 @@ | ||
| 105 | 101 | int protocolVersion = factory.protocolVersion == 1 ? 1 : 2; |
| 106 | 102 | bootstrap.handler( |
| 107 | 103 | new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(), |
| 108 | - factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds())); | |
| 104 | + factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), | |
| 105 | + factory.configuration.getNettyOptions())); | |
| 109 | 106 | |
| 110 | 107 | ChannelFuture future = bootstrap.connect(address); |
| 111 | 108 | |
| @@ -538,46 +535,11 @@ | ||
| 538 | 535 | |
| 539 | 536 | public static class Factory { |
| 540 | 537 | |
| 541 | - private static final Class[] EVENT_GROUP_ARGUMENTS = {int.class, ThreadFactory.class}; | |
| 542 | - private static final Class<? extends EventLoopGroup> EVENT_LOOP_GROUP_CLASS; | |
| 543 | - private static final Class<? extends Channel> CHANNEL_CLASS; | |
| 544 | - private static final Constructor<? extends EventLoopGroup> EVENT_LOOP_GROUP_CONSTRUCTOR; | |
| 545 | - static { | |
| 546 | - boolean useEpoll; | |
| 547 | - try { | |
| 548 | - Class.forName("io.netty.channel.epoll.EpollEventLoopGroup"); | |
| 549 | - if (FORCE_NIO) { | |
| 550 | - logger.info("Found Netty's native epoll transport in the classpath, " | |
| 551 | - + "but NIO was forced through the FORCE_NIO system property"); | |
| 552 | - useEpoll = false; | |
| 553 | - } else if(!System.getProperty("os.name", "").toLowerCase(Locale.US).equals("linux")) { | |
| 554 | - logger.warn("Found Netty's native epoll transport, but not running on linux-based operating " + | |
| 555 | - "system. Using NIO instead."); | |
| 556 | - useEpoll = false; | |
| 557 | - } else { | |
| 558 | - logger.info("Found Netty's native epoll transport in the classpath, using it"); | |
| 559 | - useEpoll = true; | |
| 560 | - } | |
| 561 | - } catch (ClassNotFoundException e) { | |
| 562 | - logger.info("Did not find Netty's native epoll transport in the classpath, defaulting to NIO"); | |
| 563 | - useEpoll = false; | |
| 564 | - } | |
| 565 | - EVENT_LOOP_GROUP_CLASS = useEpoll ? EpollEventLoopGroup.class : NioEventLoopGroup.class; | |
| 566 | - CHANNEL_CLASS = useEpoll ? EpollSocketChannel.class : NioSocketChannel.class; | |
| 567 | - | |
| 568 | - Constructor<? extends EventLoopGroup> constructor = null; | |
| 569 | - try { | |
| 570 | - constructor = EVENT_LOOP_GROUP_CLASS.getDeclaredConstructor(EVENT_GROUP_ARGUMENTS); | |
| 571 | - } catch (NoSuchMethodException e) { | |
| 572 | - logger.warn("Could not resolve {}(int, ThreadFactory), using default constructor instead.", | |
| 573 | - EVENT_LOOP_GROUP_CLASS.getName()); | |
| 574 | - } | |
| 575 | - EVENT_LOOP_GROUP_CONSTRUCTOR = constructor; | |
| 576 | - } | |
| 577 | - | |
| 578 | 538 | public final HashedWheelTimer timer; |
| 579 | 539 | |
| 580 | 540 | private final EventLoopGroup eventLoopGroup; |
| 541 | + private final Class<? extends Channel> channelClass; | |
| 542 | + | |
| 581 | 543 | private final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); |
| 582 | 544 | |
| 583 | 545 | private final ConcurrentMap<Host, AtomicInteger> idGenerators = new ConcurrentHashMap<Host, AtomicInteger>(); |
| @@ -590,6 +552,7 @@ | ||
| 590 | 552 | private volatile boolean isShutdown; |
| 591 | 553 | |
| 592 | 554 | volatile int protocolVersion; |
| 555 | + private final NettyOptions nettyOptions; | |
| 593 | 556 | |
| 594 | 557 | Factory(Cluster.Manager manager, Configuration configuration) { |
| 595 | 558 | this.defaultHandler = manager; |
| @@ -598,20 +561,9 @@ | ||
| 598 | 561 | this.configuration = configuration; |
| 599 | 562 | this.authProvider = configuration.getProtocolOptions().getAuthProvider(); |
| 600 | 563 | this.protocolVersion = configuration.getProtocolOptions().initialProtocolVersion; |
| 601 | - | |
| 602 | - try { | |
| 603 | - // Use default constructor if the specialized constructor could not be resolved. | |
| 604 | - if(EVENT_LOOP_GROUP_CONSTRUCTOR != null) { | |
| 605 | - eventLoopGroup = EVENT_LOOP_GROUP_CONSTRUCTOR.newInstance(0, manager.threadFactory("nio-worker")); | |
| 606 | - } else { | |
| 607 | - eventLoopGroup = EVENT_LOOP_GROUP_CLASS.newInstance(); | |
| 608 | - } | |
| 609 | - } catch (Exception e) { | |
| 610 | - throw new AssertionError("Could not create an instance of " | |
| 611 | - + EVENT_LOOP_GROUP_CLASS.getName() | |
| 612 | - + ", this should not happen"); | |
| 613 | - } | |
| 614 | - | |
| 564 | + this.nettyOptions = configuration.getNettyOptions(); | |
| 565 | + this.eventLoopGroup = nettyOptions.eventLoopGroup(manager.threadFactory("nio-worker")); | |
| 566 | + this.channelClass = nettyOptions.channelClass(); | |
| 615 | 567 | this.timer = new HashedWheelTimer(manager.threadFactory("timeouter")); |
| 616 | 568 | } |
| 617 | 569 | |
| @@ -671,7 +623,7 @@ | ||
| 671 | 623 | private Bootstrap newBootstrap() { |
| 672 | 624 | Bootstrap b = new Bootstrap(); |
| 673 | 625 | b.group(eventLoopGroup) |
| 674 | - .channel(CHANNEL_CLASS); | |
| 626 | + .channel(channelClass); | |
| 675 | 627 | |
| 676 | 628 | SocketOptions options = configuration.getSocketOptions(); |
| 677 | 629 | |
| @@ -695,6 +647,7 @@ | ||
| 695 | 647 | if (sendBufferSize != null) |
| 696 | 648 | b.option(ChannelOption.SO_SNDBUF, sendBufferSize); |
| 697 | 649 | |
| 650 | + nettyOptions.afterBootstrapInitialized(b); | |
| 698 | 651 | return b; |
| 699 | 652 | } |
| 700 | 653 | |
| @@ -706,9 +659,7 @@ | ||
| 706 | 659 | // we're not on an I/O thread or anything, so just call await. |
| 707 | 660 | allChannels.close().awaitUninterruptibly(); |
| 708 | 661 | |
| 709 | - // This will shut down I/O threads. Since this is called only once all connection have | |
| 710 | - // been individually closed, it's fine. | |
| 711 | - eventLoopGroup.shutdownGracefully().syncUninterruptibly(); | |
| 662 | + nettyOptions.onClusterClose(eventLoopGroup); | |
| 712 | 663 | timer.stop(); |
| 713 | 664 | } |
| 714 | 665 | } |
| @@ -1135,13 +1086,15 @@ | ||
| 1135 | 1086 | private final Connection connection; |
| 1136 | 1087 | private final FrameCompressor compressor; |
| 1137 | 1088 | private final SSLOptions sslOptions; |
| 1089 | + private final NettyOptions nettyOptions; | |
| 1138 | 1090 | private final ChannelHandler idleStateHandler; |
| 1139 | 1091 | |
| 1140 | - public Initializer(Connection connection, int protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds) { | |
| 1092 | + public Initializer(Connection connection, int protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds, NettyOptions nettyOptions) { | |
| 1141 | 1093 | this.connection = connection; |
| 1142 | 1094 | this.protocolVersion = protocolVersion; |
| 1143 | 1095 | this.compressor = compressor; |
| 1144 | 1096 | this.sslOptions = sslOptions; |
| 1097 | + this.nettyOptions = nettyOptions; | |
| 1145 | 1098 | this.idleStateHandler = new IdleStateHandler(0, 0, heartBeatIntervalSeconds); |
| 1146 | 1099 | } |
| 1147 | 1100 | |
| @@ -1173,6 +1126,8 @@ | ||
| 1173 | 1126 | pipeline.addLast("idleStateHandler", idleStateHandler); |
| 1174 | 1127 | |
| 1175 | 1128 | pipeline.addLast("dispatcher", connection.dispatcher); |
| 1129 | + | |
| 1130 | + nettyOptions.afterChannelInitialized(channel); | |
| 1176 | 1131 | } |
| 1177 | 1132 | } |
| 1178 | 1133 | } |
added driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +194 −0
| @@ -0,0 +1,194 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.util.concurrent.ThreadFactory; | |
| 19 | +import java.util.concurrent.TimeUnit; | |
| 20 | + | |
| 21 | +import static java.util.concurrent.TimeUnit.SECONDS; | |
| 22 | + | |
| 23 | +import io.netty.bootstrap.Bootstrap; | |
| 24 | +import io.netty.channel.EventLoopGroup; | |
| 25 | +import io.netty.channel.nio.NioEventLoopGroup; | |
| 26 | +import io.netty.channel.socket.SocketChannel; | |
| 27 | +import io.netty.channel.socket.nio.NioSocketChannel; | |
| 28 | + | |
| 29 | +/** | |
| 30 | + * A set of hooks that allow clients to customize the driver's underlying Netty layer. | |
| 31 | + * <p> | |
| 32 | + * Clients that need to hook into the driver's underlying Netty layer can | |
| 33 | + * subclass this class and provide the necessary customization by overriding | |
| 34 | + * its methods. | |
| 35 | + * <p> | |
| 36 | + * Typically, clients would register this class with {@link Cluster#builder()}: | |
| 37 | + * | |
| 38 | + * <pre> | |
| 39 | + * NettyOptions nettyOptions = ... | |
| 40 | + * Cluster cluster = Cluster.builder() | |
| 41 | + * .addContactPoint(...) | |
| 42 | + * .withNettyOptions(nettyOptions) | |
| 43 | + * .build(); | |
| 44 | + * </pre> | |
| 45 | + * | |
| 46 | + * <strong>Extending the NettyOptions API</strong> | |
| 47 | + * <p> | |
| 48 | + * Contrary to other driver options, the options available in this class should | |
| 49 | + * be considered as advanced features and as such, <em>they should only be | |
| 50 | + * modified by expert users</em>. | |
| 51 | + * <p> | |
| 52 | + * <strong>A misconfiguration introduced by the means of this API can have unexpected results | |
| 53 | + * and cause the driver to completely fail to connect.</strong> | |
| 54 | + * <p> | |
| 55 | + * Moreover, since versions 2.0.9 and 2.1.4 (see JAVA-538), | |
| 56 | + * the driver is available in two different flavors: with a standard Maven dependency on Netty, | |
| 57 | + * or with a "shaded" (internalized) Netty dependency. | |
| 58 | + * <p> | |
| 59 | + * Given that NettyOptions API exposes Netty classes ({@link SocketChannel}, etc.), | |
| 60 | + * <em>it should only be extended by clients using the non-shaded | |
| 61 | + * version of driver</em>. | |
| 62 | + * <p> | |
| 63 | + * <strong>Extending this API with shaded Netty classes is not supported, | |
| 64 | + * and in particular for OSGi applications, it is likely that such a configuration would lead to | |
| 65 | + * compile and/or runtime errors.</strong> | |
| 66 | + * | |
| 67 | + * @jira_ticket JAVA-640 | |
| 68 | + * @since 2.0.10 | |
| 69 | + */ | |
| 70 | +public class NettyOptions { | |
| 71 | + | |
| 72 | + /** | |
| 73 | + * The default instance of {@link NettyOptions} to use. | |
| 74 | + */ | |
| 75 | + public static final NettyOptions DEFAULT_INSTANCE = new NettyOptions(); | |
| 76 | + | |
| 77 | + /** | |
| 78 | + * Return the {@link EventLoopGroup} instance to use. | |
| 79 | + * <p> | |
| 80 | + * This hook is invoked only once at {@link Cluster} initialization; | |
| 81 | + * the returned instance will be kept in use throughout the cluster lifecycle. | |
| 82 | + * <p> | |
| 83 | + * Typically, implementors would return a newly-created instance; | |
| 84 | + * it is however possible to re-use a shared instance, but in this | |
| 85 | + * case implementors should also override {@link #onClusterClose(EventLoopGroup)} | |
| 86 | + * to prevent the shared instance to be closed when the cluster is closed. | |
| 87 | + * <p> | |
| 88 | + * The default implementation returns a new instance of {@link io.netty.channel.epoll.EpollEventLoopGroup} | |
| 89 | + * if {@link NettyUtil#isEpollAvailable() epoll is available}, | |
| 90 | + * or {@link NioEventLoopGroup} otherwise. | |
| 91 | + * | |
| 92 | + * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link EventLoopGroup} instance; | |
| 93 | + * The driver will provide its own internal thread factory here. | |
| 94 | + * It is safe to ignore it and use another thread factory. | |
| 95 | + * @return the {@link EventLoopGroup} instance to use. | |
| 96 | + */ | |
| 97 | + public EventLoopGroup eventLoopGroup(ThreadFactory threadFactory) { | |
| 98 | + return NettyUtil.newEventLoopGroupInstance(threadFactory); | |
| 99 | + } | |
| 100 | + | |
| 101 | + /** | |
| 102 | + * Return the specific {@link SocketChannel} subclass to use. | |
| 103 | + * <p> | |
| 104 | + * This hook is invoked only once at {@link Cluster} initialization; | |
| 105 | + * the returned instance will then be used each time the driver creates a new {@link Connection} | |
| 106 | + * and configures a new instance of {@link Bootstrap} for it. | |
| 107 | + * <p> | |
| 108 | + * The default implementation returns {@link io.netty.channel.epoll.EpollSocketChannel} if {@link NettyUtil#isEpollAvailable() epoll is available}, | |
| 109 | + * or {@link NioSocketChannel} otherwise. | |
| 110 | + * | |
| 111 | + * @return The {@link SocketChannel} subclass to use. | |
| 112 | + */ | |
| 113 | + public Class<? extends SocketChannel> channelClass() { | |
| 114 | + return NettyUtil.channelClass(); | |
| 115 | + } | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * Hook invoked each time the driver creates a new {@link Connection} | |
| 119 | + * and configures a new instance of {@link Bootstrap} for it. | |
| 120 | + * <p> | |
| 121 | + * This hook is guaranteed to be called <em>after</em> the driver has applied all | |
| 122 | + * {@link SocketOptions}s. | |
| 123 | + * <p> | |
| 124 | + * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelOption}s to the boostrap; e.g. | |
| 125 | + * to replace the default {@link io.netty.buffer.ByteBufAllocator ByteBufAllocator} implementation with a custom one, | |
| 126 | + * do the following: | |
| 127 | + * | |
| 128 | + * <pre> | |
| 129 | + * ByteBufAllocator myCustomByteBufAllocator = ... | |
| 130 | + * boostrap.option(ChannelOption.ALLOCATOR, myCustomByteBufAllocator); | |
| 131 | + * </pre> | |
| 132 | + * | |
| 133 | + * @param bootstrap the {@link Bootstrap} being initialized. | |
| 134 | + */ | |
| 135 | + public void afterBootstrapInitialized(Bootstrap bootstrap) { | |
| 136 | + //noop | |
| 137 | + } | |
| 138 | + | |
| 139 | + /** | |
| 140 | + * Hook invoked each time the driver creates a new {@link Connection} | |
| 141 | + * and initializes the {@link SocketChannel channel}. | |
| 142 | + * <p> | |
| 143 | + * This hook is guaranteed to be called <em>after</em> the driver has registered | |
| 144 | + * all its internal channel handlers, and applied the configured {@link SSLOptions}, if any. | |
| 145 | + * <p> | |
| 146 | + * This is a good place to add extra {@link io.netty.channel.ChannelHandler ChannelHandler}s | |
| 147 | + * to the channel's pipeline; e.g. to add a custom SSL handler to the beginning of the handler chain, | |
| 148 | + * do the following: | |
| 149 | + * | |
| 150 | + * <pre> | |
| 151 | + * ChannelPipeline pipeline = channel.pipeline(); | |
| 152 | + * SSLEngine myCustomSSLEngine = ... | |
| 153 | + * SslHandler myCustomSSLHandler = new SslHandler(myCustomSSLEngine); | |
| 154 | + * pipeline.addFirst("ssl", myCustomSSLHandler); | |
| 155 | + * </pre> | |
| 156 | + * | |
| 157 | + * Note: if you intend to provide your own SSL implementation, | |
| 158 | + * do not enable the driver's built-in {@link SSLOptions} at the same time. | |
| 159 | + * | |
| 160 | + * @param channel the {@link SocketChannel} instance, after being initialized by the driver. | |
| 161 | + * @throws Exception if this methods encounters any errors. | |
| 162 | + */ | |
| 163 | + public void afterChannelInitialized(SocketChannel channel) throws Exception { | |
| 164 | + //noop | |
| 165 | + } | |
| 166 | + | |
| 167 | + /** | |
| 168 | + * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}. | |
| 169 | + * <p> | |
| 170 | + * This is guaranteed to be called only after all connections have been individually | |
| 171 | + * closed, and their channels closed, and only once per {@link EventLoopGroup} instance. | |
| 172 | + * <p> | |
| 173 | + * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required. | |
| 174 | + * <p> | |
| 175 | + * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully(long, long, TimeUnit) graceful shutdown} | |
| 176 | + * of the passed {@link EventLoopGroup} instance with no "quiet period" and a timeout of 15 seconds; | |
| 177 | + * then waits uninterruptibly for the shutdown to complete, or the timeout to occur, whichever happens first. | |
| 178 | + * <p> | |
| 179 | + * Implementation note: if the {@link EventLoopGroup} instance is being shared, or used for other purposes than to | |
| 180 | + * coordinate Netty events for the current cluster, than it should not be shut down here; | |
| 181 | + * subclasses would have to override this method accordingly to take the appropriate action. | |
| 182 | + * | |
| 183 | + * @param eventLoopGroup the event loop group used by the cluster being closed | |
| 184 | + */ | |
| 185 | + public void onClusterClose(EventLoopGroup eventLoopGroup) { | |
| 186 | + // shutdownGracefully with default parameters employs a quiet period of 2 seconds | |
| 187 | + // where in pre-Netty4 versions, closing a cluster instance was very quick (milliseconds). | |
| 188 | + // Since we close the channels before shutting down the eventLoopGroup, | |
| 189 | + // it is safe to reduce the quiet period to 0 seconds | |
| 190 | + eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly(); | |
| 191 | + } | |
| 192 | + | |
| 193 | + | |
| 194 | +} |
added driver-core/src/main/java/com/datastax/driver/core/NettyUtil.java +160 −0
| @@ -0,0 +1,160 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.lang.reflect.Constructor; | |
| 19 | +import java.util.Locale; | |
| 20 | +import java.util.concurrent.ThreadFactory; | |
| 21 | + | |
| 22 | +import com.google.common.base.Throwables; | |
| 23 | +import io.netty.channel.EventLoopGroup; | |
| 24 | +import io.netty.channel.nio.NioEventLoopGroup; | |
| 25 | +import io.netty.channel.socket.SocketChannel; | |
| 26 | +import io.netty.channel.socket.nio.NioSocketChannel; | |
| 27 | +import org.slf4j.Logger; | |
| 28 | +import org.slf4j.LoggerFactory; | |
| 29 | + | |
| 30 | +/** | |
| 31 | + * A set of utilities related to the underlying Netty layer. | |
| 32 | + */ | |
| 33 | +@SuppressWarnings("unchecked") | |
| 34 | +class NettyUtil { | |
| 35 | + | |
| 36 | + private static final boolean FORCE_NIO = SystemProperties.getBoolean("com.datastax.driver.FORCE_NIO", false); | |
| 37 | + | |
| 38 | + private static final Logger LOGGER = LoggerFactory.getLogger(NettyUtil.class); | |
| 39 | + | |
| 40 | + private static final boolean SHADED; | |
| 41 | + | |
| 42 | + private static final boolean USE_EPOLL; | |
| 43 | + | |
| 44 | + private static final Constructor<? extends EventLoopGroup> EPOLL_EVENT_LOOP_GROUP_CONSTRUCTOR; | |
| 45 | + | |
| 46 | + private static final Class<? extends SocketChannel> EPOLL_CHANNEL_CLASS; | |
| 47 | + | |
| 48 | + private static final Class[] EVENT_GROUP_ARGUMENTS = { int.class, ThreadFactory.class }; | |
| 49 | + | |
| 50 | + static { | |
| 51 | + boolean shaded; | |
| 52 | + try { | |
| 53 | + // prevent this string from being shaded | |
| 54 | + Class.forName(String.format("%s.%s.channel.Channel", "io", "netty")); | |
| 55 | + shaded = false; | |
| 56 | + } catch (ClassNotFoundException e) { | |
| 57 | + try { | |
| 58 | + Class.forName("com.datastax.shaded.netty.channel.Channel"); | |
| 59 | + shaded = true; | |
| 60 | + } catch (ClassNotFoundException e1) { | |
| 61 | + throw new AssertionError("Cannot locate Netty classes in the classpath:" + e1); | |
| 62 | + } | |
| 63 | + } | |
| 64 | + SHADED = shaded; | |
| 65 | + boolean useEpoll = false; | |
| 66 | + if (!SHADED) { | |
| 67 | + try { | |
| 68 | + Class<?> epoll = Class.forName("io.netty.channel.epoll.Epoll"); | |
| 69 | + if (FORCE_NIO) { | |
| 70 | + LOGGER.info("Found Netty's native epoll transport in the classpath, " | |
| 71 | + + "but NIO was forced through the FORCE_NIO system property."); | |
| 72 | + } else if (!System.getProperty("os.name", "").toLowerCase(Locale.US).equals("linux")) { | |
| 73 | + LOGGER.warn("Found Netty's native epoll transport, but not running on linux-based operating " + | |
| 74 | + "system. Using NIO instead."); | |
| 75 | + } else if (!(Boolean)epoll.getMethod("isAvailable").invoke(null)) { | |
| 76 | + LOGGER.warn("Found Netty's native epoll transport in the classpath, but epoll is not available. " | |
| 77 | + + "Using NIO instead.", (Throwable)epoll.getMethod("unavailabilityCause").invoke(null)); | |
| 78 | + } else { | |
| 79 | + LOGGER.info("Found Netty's native epoll transport in the classpath, using it"); | |
| 80 | + useEpoll = true; | |
| 81 | + } | |
| 82 | + } catch (ClassNotFoundException e) { | |
| 83 | + LOGGER.info("Did not find Netty's native epoll transport in the classpath, defaulting to NIO."); | |
| 84 | + } catch (Exception e) { | |
| 85 | + LOGGER.warn("Unexpected error trying to find Netty's native epoll transport in the classpath, defaulting to NIO.", e); | |
| 86 | + } | |
| 87 | + } else { | |
| 88 | + LOGGER.info("Detected shaded Netty classes in the classpath; native epoll transport will not work properly, " | |
| 89 | + + "defaulting to NIO."); | |
| 90 | + } | |
| 91 | + USE_EPOLL = useEpoll; | |
| 92 | + Constructor<? extends EventLoopGroup> constructor = null; | |
| 93 | + Class<? extends SocketChannel> channelClass = null; | |
| 94 | + if (USE_EPOLL) { | |
| 95 | + try { | |
| 96 | + channelClass = (Class<? extends SocketChannel>)Class.forName("io.netty.channel.epoll.EpollSocketChannel"); | |
| 97 | + Class<?> epoolEventLoupGroupClass = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup"); | |
| 98 | + constructor = (Constructor<? extends EventLoopGroup>)epoolEventLoupGroupClass.getDeclaredConstructor(EVENT_GROUP_ARGUMENTS); | |
| 99 | + } catch (Exception e) { | |
| 100 | + throw new AssertionError("Netty's native epoll is in use but cannot locate Epoll classes, this should not happen: " + e); | |
| 101 | + } | |
| 102 | + } | |
| 103 | + EPOLL_EVENT_LOOP_GROUP_CONSTRUCTOR = constructor; | |
| 104 | + EPOLL_CHANNEL_CLASS = channelClass; | |
| 105 | + } | |
| 106 | + | |
| 107 | + /** | |
| 108 | + * | |
| 109 | + * @return true if the current driver bundle is using shaded Netty classes, false otherwise. | |
| 110 | + */ | |
| 111 | + | |
| 112 | + public static boolean isShaded() { | |
| 113 | + return SHADED; | |
| 114 | + } | |
| 115 | + | |
| 116 | + /** | |
| 117 | + * @return true if native epoll transport is available in the classpath, false otherwise. | |
| 118 | + */ | |
| 119 | + public static boolean isEpollAvailable() { | |
| 120 | + return USE_EPOLL; | |
| 121 | + } | |
| 122 | + | |
| 123 | + /** | |
| 124 | + * Return a new instance of {@link EventLoopGroup}. | |
| 125 | + * <p> | |
| 126 | + * Returns an instance of {@link io.netty.channel.epoll.EpollEventLoopGroup} if {@link #isEpollAvailable() epoll is available}, | |
| 127 | + * or an instance of {@link NioEventLoopGroup} otherwise. | |
| 128 | + * | |
| 129 | + * @param factory the {@link ThreadFactory} instance to use to create the new instance of {@link EventLoopGroup} | |
| 130 | + * @return a new instance of {@link EventLoopGroup} | |
| 131 | + */ | |
| 132 | + public static EventLoopGroup newEventLoopGroupInstance(ThreadFactory factory) { | |
| 133 | + if (isEpollAvailable()) { | |
| 134 | + try { | |
| 135 | + return EPOLL_EVENT_LOOP_GROUP_CONSTRUCTOR.newInstance(0, factory); | |
| 136 | + } catch (Exception e) { | |
| 137 | + throw Throwables.propagate(e); // should not happen | |
| 138 | + } | |
| 139 | + } else { | |
| 140 | + return new NioEventLoopGroup(0, factory); | |
| 141 | + } | |
| 142 | + } | |
| 143 | + | |
| 144 | + /** | |
| 145 | + * Return the SocketChannel class to use. | |
| 146 | + * <p> | |
| 147 | + * Returns an instance of {@link io.netty.channel.epoll.EpollSocketChannel} if {@link #isEpollAvailable() epoll is available}, | |
| 148 | + * or an instance of {@link NioSocketChannel} otherwise. | |
| 149 | + * | |
| 150 | + * @return the SocketChannel class to use. | |
| 151 | + */ | |
| 152 | + public static Class<? extends SocketChannel> channelClass() { | |
| 153 | + if (isEpollAvailable()) { | |
| 154 | + return EPOLL_CHANNEL_CLASS; | |
| 155 | + } else { | |
| 156 | + return NioSocketChannel.class; | |
| 157 | + } | |
| 158 | + } | |
| 159 | + | |
| 160 | +} |
added driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +95 −0
| @@ -0,0 +1,95 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.util.concurrent.ThreadFactory; | |
| 19 | + | |
| 20 | +import io.netty.bootstrap.Bootstrap; | |
| 21 | +import io.netty.channel.ChannelHandler; | |
| 22 | +import io.netty.channel.ChannelHandlerContext; | |
| 23 | +import io.netty.channel.EventLoopGroup; | |
| 24 | +import io.netty.channel.nio.NioEventLoopGroup; | |
| 25 | +import io.netty.channel.socket.SocketChannel; | |
| 26 | +import org.mockito.ArgumentCaptor; | |
| 27 | +import org.mockito.invocation.InvocationOnMock; | |
| 28 | +import org.mockito.stubbing.Answer; | |
| 29 | +import org.testng.annotations.DataProvider; | |
| 30 | +import org.testng.annotations.Test; | |
| 31 | + | |
| 32 | +import static org.mockito.Answers.CALLS_REAL_METHODS; | |
| 33 | +import static org.mockito.Matchers.any; | |
| 34 | +import static org.mockito.Mockito.*; | |
| 35 | + | |
| 36 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 37 | +import static com.datastax.driver.core.CCMBridge.ipOfNode; | |
| 38 | + | |
| 39 | +public class NettyOptionsTest { | |
| 40 | + | |
| 41 | + @DataProvider(name = "NettyOptionsTest") | |
| 42 | + public static Object[][] parameters() { | |
| 43 | + Object[][] params = new Object[][] { {1,1}, {3,4} }; | |
| 44 | + return params; | |
| 45 | + } | |
| 46 | + | |
| 47 | + @Test(groups = "short", dataProvider = "NettyOptionsTest") | |
| 48 | + public void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception { | |
| 49 | + //given | |
| 50 | + int expectedNumberOfCalls = coreConnections * hosts + 1; | |
| 51 | + CCMBridge ccm = CCMBridge.createWithCustomVersion("test", hosts, "2.0.10"); | |
| 52 | + Cluster cluster = null; | |
| 53 | + try { | |
| 54 | + NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get()); | |
| 55 | + EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); | |
| 56 | + when(nettyOptions.eventLoopGroup(any(ThreadFactory.class))).thenReturn(eventLoopGroup); | |
| 57 | + final ChannelHandler handler = mock(ChannelHandler.class); | |
| 58 | + doAnswer(new Answer() { | |
| 59 | + @Override | |
| 60 | + public Object answer(InvocationOnMock invocation) throws Throwable { | |
| 61 | + SocketChannel channel = (SocketChannel) invocation.getArguments()[0]; | |
| 62 | + channel.pipeline().addLast("test-handler", handler); | |
| 63 | + return null; | |
| 64 | + } | |
| 65 | + }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class)); | |
| 66 | + cluster = Cluster.builder() | |
| 67 | + .addContactPoint(ipOfNode(1)) | |
| 68 | + .withPoolingOptions(new PoolingOptions() | |
| 69 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections) | |
| 70 | + ) | |
| 71 | + .withNettyOptions(nettyOptions) | |
| 72 | + .build(); | |
| 73 | + // when | |
| 74 | + cluster.connect();// force session creation to populate pools | |
| 75 | + cluster.close(); | |
| 76 | + // then | |
| 77 | + ArgumentCaptor<EventLoopGroup> captor = ArgumentCaptor.forClass(EventLoopGroup.class); | |
| 78 | + verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class)); | |
| 79 | + verify(nettyOptions, times(1)).channelClass(); | |
| 80 | + // per-connection hooks will be called coreConnections * hosts + 1 times: | |
| 81 | + // the extra call is for the control connection | |
| 82 | + verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class)); | |
| 83 | + verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class)); | |
| 84 | + verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class)); | |
| 85 | + verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class)); | |
| 86 | + verify(nettyOptions, times(1)).onClusterClose(captor.capture()); | |
| 87 | + assertThat(captor.getValue()).isSameAs(eventLoopGroup); | |
| 88 | + } finally { | |
| 89 | + if (cluster != null) | |
| 90 | + cluster.close(); | |
| 91 | + ccm.remove(); | |
| 92 | + } | |
| 93 | + } | |
| 94 | + | |
| 95 | +} | |
| No newline at the end of the file |