Elffuss BraidHub

kikocis/java-driver public

Merge pull request #268 from datastax/java533

Add connection heartbeat (JAVA-533).
Changesetf3def2c54d3f1a9efc858fdd0c7e8ff03c80726176c3375363f684e82544f8d5
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-03 14:14 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-02-03 14:14 +01:00
Parentsf3abadd1b89d, 723a42276606

Browse the files at this changeset

6 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 +139 −0
@@ -0,0 +1,139 @@
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+ /**
32+ * Ensures that a heartbeat message is sent after the configured heartbeat interval of idle time and succeeds and
33+ * continues to be sent as long as the connection remains idle.
34+ *
35+ * @test_category connection:heartbeat
36+ * @expected_result heartbeat is sent after heartbeat interval (3) seconds of idle time.
37+ * @jira_ticket JAVA-533
38+ * @since 2.0.10, 2.1.5
39+ */
40+ @Test(groups = "long")
41+ public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException {
42+ CCMBridge ccm = null;
43+ Cluster cluster = null;
44+ try {
45+ ccm = CCMBridge.create("test", 1);
46+ cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
47+ .withPoolingOptions(new PoolingOptions()
48+ .setHeartbeatIntervalSeconds(3))
49+ .build();
50+
51+ // Don't create any session, only the control connection will be established
52+ cluster.init();
53+
54+ for (int i = 0; i < 5; i++) {
55+ triggerRequestOnControlConnection(cluster);
56+ SECONDS.sleep(1);
57+ }
58+ assertThat(logs.getNext()).doesNotContain("sending heartbeat");
59+
60+ // Ensure heartbeat is sent after no activity.
61+ SECONDS.sleep(4);
62+ assertThat(logs.getNext())
63+ .contains("sending heartbeat")
64+ .contains("heartbeat query succeeded");
65+
66+ // Ensure heartbeat is sent after continued inactivity.
67+ SECONDS.sleep(4);
68+ assertThat(logs.getNext())
69+ .contains("sending heartbeat")
70+ .contains("heartbeat query succeeded");
71+
72+ // Ensure heartbeat is not sent after activity.
73+ logs.getNext();
74+ for (int i = 0; i < 5; i++) {
75+ triggerRequestOnControlConnection(cluster);
76+ SECONDS.sleep(1);
77+ }
78+ assertThat(logs.getNext()).doesNotContain("sending heartbeat");
79+
80+ // Finally, ensure heartbeat is sent after inactivity.
81+ SECONDS.sleep(4);
82+ assertThat(logs.getNext())
83+ .contains("sending heartbeat")
84+ .contains("heartbeat query succeeded");
85+ } finally {
86+ if (cluster != null)
87+ cluster.close();
88+ if (ccm != null)
89+ ccm.remove();
90+ }
91+ }
92+
93+ /**
94+ * Ensures that a heartbeat message is not sent if the configured heartbeat interval is 0.
95+ *
96+ * While difficult to prove the absence of evidence, the test will wait up to the default heartbeat interval
97+ * (30 seconds + 1) and check to see if the heartbeat was sent.
98+ *
99+ * @test_category connection:heartbeat
100+ * @expected_result heartbeat is not sent after default heartbeat interval (60) seconds of idle time.
101+ * @jira_ticket JAVA-533
102+ * @since 2.0.10, 2.1.5
103+ */
104+ @Test(groups = "long")
105+ public void should_not_send_heartbeat_when_disabled() throws InterruptedException {
106+ CCMBridge ccm = null;
107+ Cluster cluster = null;
108+ try {
109+ ccm = CCMBridge.create("test", 1);
110+ cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1))
111+ .withPoolingOptions(new PoolingOptions()
112+ .setHeartbeatIntervalSeconds(0))
113+ .build();
114+
115+ // Don't create any session, only the control connection will be established
116+ cluster.init();
117+
118+ for (int i = 0; i < 5; i++) {
119+ triggerRequestOnControlConnection(cluster);
120+ SECONDS.sleep(1);
121+ }
122+ assertThat(logs.get()).doesNotContain("sending heartbeat");
123+
124+ // Sleep for a while and ensure no heartbeat is sent.
125+ SECONDS.sleep(32);
126+ assertThat(logs.get()).doesNotContain("sending heartbeat");
127+ } finally {
128+ if (cluster != null)
129+ cluster.close();
130+ if (ccm != null)
131+ ccm.remove();
132+ }
133+ }
134+
135+ // Simulates activity on the control connection via the internal API
136+ private void triggerRequestOnControlConnection(Cluster cluster) {
137+ cluster.manager.controlConnection.refreshNodeInfo(TestUtils.findHost(cluster, 1));
138+ }
139+}
modified driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +11 −0
@@ -14,6 +14,8 @@
1414 public class MemoryAppender extends WriterAppender {
1515 public final StringWriter writer = new StringWriter();
1616
17+ private int nextLogIdx = 0;
18+
1719 public MemoryAppender() {
1820 setWriter(writer);
1921 setLayout(new PatternLayout("%m%n"));
@@ -22,4 +24,13 @@
2224 public String get() {
2325 return writer.toString();
2426 }
27+
28+ /**
29+ * @return The next set of logs after getNext was last called. Not thread safe.
30+ */
31+ public String getNext() {
32+ String next = get().substring(nextLogIdx);
33+ nextLogIdx += next.length();
34+ return next;
35+ }
2536 }
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")