Elffuss BraidHub

kikocis/java-driver public

Add connection heartbeat (JAVA-533).
Changeset59d6d54613bad9b8dc2a85080425c809e9a32cf1983f076475377d0fe077abf8
Authorolim7t <omichallat+github@gmail.com> · 2014-11-10 19:38 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-02-03 14:10 +01:00
Parentsf3abadd1b89d

Browse the files at this changeset

5 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -5,6 +5,7 @@
55 -------
66
77 - [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
8+- [improvement] Add connection heartbeat (JAVA-533)
89
910 Merged from 2.0.9_fixes branch:
1011
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +56 −3
@@ -31,6 +31,9 @@
3131 import org.jboss.netty.channel.group.DefaultChannelGroup;
3232 import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
3333 import org.jboss.netty.handler.ssl.SslHandler;
34+import org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler;
35+import org.jboss.netty.handler.timeout.IdleStateEvent;
36+import org.jboss.netty.handler.timeout.IdleStateHandler;
3437 import org.jboss.netty.util.HashedWheelTimer;
3538 import org.jboss.netty.util.Timeout;
3639 import org.jboss.netty.util.TimerTask;
@@ -88,7 +91,8 @@
8891 ClientBootstrap bootstrap = factory.newBootstrap();
8992 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
9093 int protocolVersion = factory.protocolVersion == 1 ? 1 : 2;
91- bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions()));
94+ bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions(),
95+ factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), factory.timer));
9296
9397 ChannelFuture future = bootstrap.connect(address);
9498
@@ -623,7 +627,7 @@
623627 }
624628 }
625629
626- private class Dispatcher extends SimpleChannelUpstreamHandler {
630+ private class Dispatcher extends IdleStateAwareChannelUpstreamHandler {
627631
628632 public final StreamIdGenerator streamIdHandler = new StreamIdGenerator();
629633 private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
@@ -704,6 +708,12 @@
704708 }
705709 }
706710
711+ @Override
712+ public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
713+ logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
714+ write(HEARTBEAT_CALLBACK);
715+ }
716+
707717 // Make sure we don't print huge responses in debug/error logs.
708718 private String asDebugString(Object obj) {
709719 if (obj == null)
@@ -752,6 +762,45 @@
752762 }
753763 }
754764
765+ private static final ResponseCallback HEARTBEAT_CALLBACK = new ResponseCallback() {
766+
767+ @Override
768+ public Message.Request request() {
769+ return new Requests.Options();
770+ }
771+
772+ @Override
773+ public int retryCount() {
774+ return 0; // no retries here
775+ }
776+
777+ @Override
778+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
779+ switch (response.type) {
780+ case SUPPORTED:
781+ logger.debug("{} heartbeat query succeeded", connection);
782+ break;
783+ default:
784+ fail(connection, new ConnectionException(connection.address, "Unexpected heartbeat response: " + response));
785+ }
786+ }
787+
788+ @Override
789+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
790+ // Nothing to do: the connection is already defunct if we arrive here
791+ }
792+
793+ @Override
794+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
795+ fail(connection, new ConnectionException(connection.address, "Heartbeat query timed out"));
796+ return true;
797+ }
798+
799+ private void fail(Connection connection, Exception e) {
800+ connection.defunct(e);
801+ }
802+ };
803+
755804 private class ConnectionCloseFuture extends CloseFuture {
756805
757806 @Override
@@ -913,12 +962,14 @@
913962 private final Connection connection;
914963 private final FrameCompressor compressor;
915964 private final SSLOptions sslOptions;
965+ private final ChannelHandler idleStateHandler;
916966
917- public PipelineFactory(Connection connection, int protocolVersion, FrameCompressor compressor, SSLOptions sslOptions) {
967+ public PipelineFactory(Connection connection, int protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds, HashedWheelTimer timer) {
918968 this.connection = connection;
919969 this.protocolVersion = protocolVersion;
920970 this.compressor = compressor;
921971 this.sslOptions = sslOptions;
972+ this.idleStateHandler = new IdleStateHandler(timer, 0, 0, heartBeatIntervalSeconds);
922973 }
923974
924975 @Override
@@ -947,6 +998,8 @@
947998 pipeline.addLast("messageDecoder", messageDecoder);
948999 pipeline.addLast("messageEncoder", protocolVersion == 1 ? messageEncoderV1 : messageEncoderV2);
9491000
1001+ pipeline.addLast("idleStateHandler", idleStateHandler);
1002+
9501003 pipeline.addLast("dispatcher", connection.dispatcher);
9511004
9521005 return pipeline;
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +33 −0
@@ -58,6 +58,7 @@
5858 private static final int DEFAULT_MAX_POOL_REMOTE = 2;
5959
6060 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
61+ private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
6162
6263 private volatile Cluster.Manager manager;
6364
@@ -68,6 +69,7 @@
6869 private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
6970
7071 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
72+ private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
7173
7274 public PoolingOptions() {}
7375
@@ -266,6 +268,37 @@
266268 return this;
267269 }
268270
271+ /**
272+ * Returns the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
273+ * @return the interval.
274+ */
275+ public int getHeartbeatIntervalSeconds() {
276+ return heartbeatIntervalSeconds;
277+ }
278+
279+ /**
280+ * Sets the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive.
281+ * <p>
282+ * This is an application-level keep-alive, provided for convenience since adjusting the TCP keep-alive might not be
283+ * practical in all environments.
284+ * <p>
285+ * This option should be set higher than {@link SocketOptions#getReadTimeoutMillis()}.
286+ * <p>
287+ * The default value for this option is 30 seconds.
288+ *
289+ * @param heartbeatIntervalSeconds the new value in seconds. If set to 0, it will disable the feature.
290+ * @return this {@code PoolingOptions}
291+ *
292+ * @throws IllegalArgumentException if the interval is negative.
293+ */
294+ public PoolingOptions setHeartbeatIntervalSeconds(int heartbeatIntervalSeconds) {
295+ if (poolTimeoutMillis < 0)
296+ throw new IllegalArgumentException("Heartbeat interval must be positive");
297+
298+ this.heartbeatIntervalSeconds = heartbeatIntervalSeconds;
299+ return this;
300+ }
301+
269302 /**
270303 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
271304 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
added driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +63 −0
@@ -0,0 +1,63 @@
1+package com.datastax.driver.core;
2+
3+import static java.util.concurrent.TimeUnit.SECONDS;
4+
5+import org.apache.log4j.Level;
6+import org.apache.log4j.Logger;
7+import org.testng.annotations.AfterMethod;
8+import org.testng.annotations.BeforeMethod;
9+import org.testng.annotations.Test;
10+
11+import static com.datastax.driver.core.Assertions.assertThat;
12+
13+public class HeartbeatTest {
14+
15+ Logger connectionLogger = Logger.getLogger(Connection.class);
16+ MemoryAppender logs;
17+
18+ @BeforeMethod(groups = "long")
19+ public void startCapturingLogs() {
20+ connectionLogger.setLevel(Level.DEBUG);
21+ logs = new MemoryAppender();
22+ connectionLogger.addAppender(logs);
23+ }
24+
25+ @AfterMethod(groups="long")
26+ public void stopCapturingLogs() {
27+ connectionLogger.setLevel(null);
28+ connectionLogger.removeAppender(logs);
29+ }
30+
31+ @Test(groups = "long")
32+ public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException {
33+ CCMBridge ccm = null;
34+ Cluster cluster = null;
35+ try {
36+ ccm = CCMBridge.create("test", 1);
37+ cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
38+ .withPoolingOptions(new PoolingOptions()
39+ .setHeartbeatIntervalSeconds(3))
40+ .build();
41+
42+ // Don't create any session, only the control connection will be established
43+ cluster.init();
44+
45+ for (int i = 0; i < 5; i++) {
46+ // Simulate activity
47+ cluster.manager.controlConnection.refreshNodeInfo(TestUtils.findHost(cluster, 1));
48+ SECONDS.sleep(1);
49+ }
50+ assertThat(logs.get()).doesNotContain("sending heartbeat");
51+
52+ SECONDS.sleep(5);
53+ assertThat(logs.get())
54+ .contains("sending heartbeat")
55+ .contains("heartbeat query succeeded");
56+ } finally {
57+ if (cluster != null)
58+ cluster.close();
59+ if (ccm != null)
60+ ccm.remove();
61+ }
62+ }
63+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +4 −6
@@ -14,6 +14,7 @@
1414 import com.datastax.driver.core.*;
1515
1616 public class DCAwareRoundRobinPolicyTest {
17+ Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class);
1718 MemoryAppender logs;
1819 CCMBridge ccm;
1920
@@ -31,18 +32,15 @@
3132
3233 @BeforeMethod(groups = "short")
3334 public void startRecordingLogs() {
34- Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class);
35- assertThat(Level.WARN.isGreaterOrEqual(policyLogger.getEffectiveLevel()))
36- .isTrue()
37- .as("Log level must be at least WARN for this test to work");
38-
35+ policyLogger.setLevel(Level.WARN);
3936 logs = new MemoryAppender();
4037 policyLogger.addAppender(logs);
4138 }
4239
4340 @AfterMethod(groups = "short")
4441 public void stopRecordingLogs() {
45- Logger.getLogger(DCAwareRoundRobinPolicy.class).removeAppender(logs);
42+ policyLogger.setLevel(null);
43+ policyLogger.removeAppender(logs);
4644 }
4745
4846 @Test(groups = "short")