Elffuss BraidHub

kikocis/java-driver public

Add request throttling on v3 connections (JAVA-364).
Changeset06bb5a3632933934fcccfaeef77f56149e23be60376dd518c6a1e9e22a1ba5d2
Authorolim7t <omichallat+github@gmail.com> · 2014-10-08 14:05 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-08 14:39 +02:00
Parentse0b476ff072a

Browse the files at this changeset

4 files changed

modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +93 −23
@@ -16,8 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 /**
19- * Options related to connection pooling when protocol version
20- * {@link ProtocolVersion#V2} or below is in use.
19+ * Options related to connection pooling.
2120 * <p>
2221 * The driver uses connections in an asynchronous manner. Meaning that
2322 * multiple requests can be submitted on the same connection at the same
@@ -25,7 +24,7 @@
2524 * small number of connections to each Cassandra host. These options allow
2625 * the driver to control how many connections are kept exactly.
2726 * <p>
28- * <b>With {code ProtocolVersion#V2} or below:</b>
27+ * <b>With {@code ProtocolVersion#V2} or below:</b>
2928 * for each host, the driver keeps a core pool of connections open at all
3029 * times determined by calling ({@link #getCoreConnectionsPerHost}).
3130 * If the use of those connections reaches a configurable threshold
@@ -36,21 +35,19 @@
3635 * reclaimed if the use of opened connections drops below the
3736 * configured threshold ({@link #getMinSimultaneousRequestsPerConnectionThreshold}).
3837 * <p>
38+ * <b>With {@code ProtocolVersion#V3} or above:</b>
39+ * the driver uses a single connection for each {@code LOCAL} or {@code REMOTE}
40+ * host. This connection can handle a larger amount of simultaneous requests,
41+ * limited by {@link #getMaxSimultaneousRequestsPerHostThreshold(HostDistance)}.
42+ * <p>
3943 * Each of these parameters can be separately set for {@code LOCAL} and
4044 * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts,
4145 * the default for all those settings is 0 and cannot be changed.
42- * <p>
43- * <b>With {code ProtocolVersion#V3} or above:</b>
44- * the driver uses a single connection for each {@code LOCAL} or {@code REMOTE}
45- * host (basically because it can submit more requests per connection).
46- * The parameters in this class do not apply, and changing them has no effect.
4746 */
4847 public class PoolingOptions {
4948
50- // Note: we could use an enumMap or similar, but synchronization would
51- // be more costly so let's stick to volatile in for now.
52- private static final int DEFAULT_MIN_REQUESTS = 25;
53- private static final int DEFAULT_MAX_REQUESTS = 100;
49+ private static final int DEFAULT_MIN_REQUESTS_PER_CONNECTION = 25;
50+ private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 100;
5451
5552 private static final int DEFAULT_CORE_POOL_LOCAL = 2;
5653 private static final int DEFAULT_CORE_POOL_REMOTE = 1;
@@ -58,16 +55,21 @@
5855 private static final int DEFAULT_MAX_POOL_LOCAL = 8;
5956 private static final int DEFAULT_MAX_POOL_REMOTE = 2;
6057
61- private static final int MAX_STREAM_PER_CONNECTION_V2 = 128;
58+ private static final int DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL = 8192;
59+ private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256;
6260
6361 private volatile Cluster.Manager manager;
6462
65- private final int[] minSimultaneousRequests = new int[]{ DEFAULT_MIN_REQUESTS, DEFAULT_MIN_REQUESTS, 0 };
66- private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 };
63+ private final int[] minSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MIN_REQUESTS_PER_CONNECTION, DEFAULT_MIN_REQUESTS_PER_CONNECTION, 0 };
64+ private final int[] maxSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MAX_REQUESTS_PER_CONNECTION, DEFAULT_MAX_REQUESTS_PER_CONNECTION, 0 };
6765
6866 private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
6967 private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
7068
69+ private volatile int maxSimultaneousRequestsPerHostLocal = DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL;
70+ private volatile int maxSimultaneousRequestsPerHostRemote = DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE;
71+
72+
7173 public PoolingOptions() {}
7274
7375 void register(Cluster.Manager manager) {
@@ -78,6 +80,8 @@
7880 * Returns the number of simultaneous requests on a connection below which
7981 * connections in excess are reclaimed.
8082 * <p>
83+ * This option is only used with {@code ProtocolVersion#V2} or below.
84+ * <p>
8185 * If an opened connection to an host at distance {@code distance}
8286 * handles less than this number of simultaneous requests and there is
8387 * more than {@link #getCoreConnectionsPerHost} connections open to this
@@ -90,12 +94,14 @@
9094 * @return the configured threshold, or the default one if none have been set.
9195 */
9296 public int getMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
93- return minSimultaneousRequests[distance.ordinal()];
97+ return minSimultaneousRequestsPerConnection[distance.ordinal()];
9498 }
9599
96100 /**
97101 * Sets the number of simultaneous requests on a connection below which
98102 * connections in excess are reclaimed.
103+ * <p>
104+ * This option is only used with {@code ProtocolVersion#V2} or below.
99105 *
100106 * @param distance the {@code HostDistance} for which to configure this threshold.
101107 * @param newMinSimultaneousRequests the value to set (between 0 and 128).
@@ -109,8 +115,8 @@
109115 throw new IllegalArgumentException("Cannot set min simultaneous requests per connection threshold for " + distance + " hosts");
110116
111117 checkRequestsPerConnectionRange(newMinSimultaneousRequests, "Min simultaneous requests per connection", distance);
112- checkRequestsPerConnectionOrder(newMinSimultaneousRequests, maxSimultaneousRequests[distance.ordinal()], distance);
113- minSimultaneousRequests[distance.ordinal()] = newMinSimultaneousRequests;
118+ checkRequestsPerConnectionOrder(newMinSimultaneousRequests, maxSimultaneousRequestsPerConnection[distance.ordinal()], distance);
119+ minSimultaneousRequestsPerConnection[distance.ordinal()] = newMinSimultaneousRequests;
114120 return this;
115121 }
116122
@@ -118,6 +124,8 @@
118124 * Returns the number of simultaneous requests on all connections to an host after
119125 * which more connections are created.
120126 * <p>
127+ * This option is only used with {@code ProtocolVersion#V2} or below.
128+ * <p>
121129 * If all the connections opened to an host at distance {@code
122130 * distance} connection are handling more than this number of
123131 * simultaneous requests and there is less than
@@ -134,12 +142,14 @@
134142 * @return the configured threshold, or the default one if none have been set.
135143 */
136144 public int getMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
137- return maxSimultaneousRequests[distance.ordinal()];
145+ return maxSimultaneousRequestsPerConnection[distance.ordinal()];
138146 }
139147
140148 /**
141149 * Sets number of simultaneous requests on all connections to an host after
142150 * which more connections are created.
151+ * <p>
152+ * This option is only used with {@code ProtocolVersion#V2} or below.
143153 *
144154 * @param distance the {@code HostDistance} for which to configure this threshold.
145155 * @param newMaxSimultaneousRequests the value to set (between 0 and 128).
@@ -153,14 +163,16 @@
153163 throw new IllegalArgumentException("Cannot set max simultaneous requests per connection threshold for " + distance + " hosts");
154164
155165 checkRequestsPerConnectionRange(newMaxSimultaneousRequests, "Max simultaneous requests per connection", distance);
156- checkRequestsPerConnectionOrder(minSimultaneousRequests[distance.ordinal()], newMaxSimultaneousRequests, distance);
157- maxSimultaneousRequests[distance.ordinal()] = newMaxSimultaneousRequests;
166+ checkRequestsPerConnectionOrder(minSimultaneousRequestsPerConnection[distance.ordinal()], newMaxSimultaneousRequests, distance);
167+ maxSimultaneousRequestsPerConnection[distance.ordinal()] = newMaxSimultaneousRequests;
158168 return this;
159169 }
160170
161171 /**
162172 * Returns the core number of connections per host.
163173 * <p>
174+ * This option is only used with {@code ProtocolVersion#V2} or below.
175+ * <p>
164176 * For the provided {@code distance}, this correspond to the number of
165177 * connections initially created and kept open to each host of that
166178 * distance.
@@ -174,6 +186,8 @@
174186
175187 /**
176188 * Sets the core number of connections per host.
189+ * <p>
190+ * This option is only used with {@code ProtocolVersion#V2} or below.
177191 *
178192 * @param distance the {@code HostDistance} for which to set this threshold.
179193 * @param newCoreConnections the value to set
@@ -197,6 +211,8 @@
197211 /**
198212 * Returns the maximum number of connections per host.
199213 * <p>
214+ * This option is only used with {@code ProtocolVersion#V2} or below.
215+ * <p>
200216 * For the provided {@code distance}, this correspond to the maximum
201217 * number of connections that can be created per host at that distance.
202218 *
@@ -209,6 +225,8 @@
209225
210226 /**
211227 * Sets the maximum number of connections per host.
228+ * <p>
229+ * This option is only used with {@code ProtocolVersion#V2} or below.
212230 *
213231 * @param distance the {@code HostDistance} for which to set this threshold.
214232 * @param newMaxConnections the value to set
@@ -226,6 +244,58 @@
226244 return this;
227245 }
228246
247+ /**
248+ * Returns the maximum number of requests per host.
249+ * <p>
250+ * This option is only used with {@code ProtocolVersion#V3} or above.
251+ * <p>
252+ * The default value for this option is 8192 for {@code LOCAL} and 256 for
253+ * {@code REMOTE} hosts.
254+ *
255+ * @param distance the {@code HostDistance} for which to return this threshold.
256+ * @return the maximum number of requests per host at distance {@code distance}.
257+ */
258+ public int getMaxSimultaneousRequestsPerHostThreshold(HostDistance distance) {
259+ switch (distance) {
260+ case LOCAL:
261+ return maxSimultaneousRequestsPerHostLocal;
262+ case REMOTE:
263+ return maxSimultaneousRequestsPerHostRemote;
264+ default:
265+ return 0;
266+ }
267+ }
268+
269+ /**
270+ * Sets the maximum number of requests per host.
271+ * <p>
272+ * This option is only used with {@code ProtocolVersion#V3} or above.
273+ *
274+ * @param distance the {@code HostDistance} for which to set this threshold.
275+ * @param newMaxRequests the value to set (between 1 and 32768).
276+ * @return this {@code PoolingOptions}.
277+ *
278+ * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
279+ * or if {@code newMaxConnections} is not within the allowed range.
280+ */
281+ public PoolingOptions setMaxSimultaneousRequestsPerHostThreshold(HostDistance distance, int newMaxRequests) {
282+ if (newMaxRequests <= 0 || newMaxRequests > StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3)
283+ throw new IllegalArgumentException(String.format("Max requests must be in the range (1, %d)",
284+ StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3));
285+
286+ switch (distance) {
287+ case LOCAL:
288+ maxSimultaneousRequestsPerHostLocal = newMaxRequests;
289+ break;
290+ case REMOTE:
291+ maxSimultaneousRequestsPerHostRemote = newMaxRequests;
292+ break;
293+ default:
294+ throw new IllegalArgumentException("Cannot set max requests per host for " + distance + " hosts");
295+ }
296+ return this;
297+ }
298+
229299 /**
230300 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
231301 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
@@ -236,10 +306,10 @@
236306 }
237307
238308 private static void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
239- if (value < 0 || value > MAX_STREAM_PER_CONNECTION_V2)
309+ if (value < 0 || value > StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2)
240310 throw new IllegalArgumentException(String.format("%s for %s hosts must be in the range (0, %d)",
241311 description, distance,
242- MAX_STREAM_PER_CONNECTION_V2));
312+ StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2));
243313 }
244314
245315 private static void checkRequestsPerConnectionOrder(int min, int max, HostDistance distance) {
modified driver-core/src/main/java/com/datastax/driver/core/SingleConnectionPool.java +8 −2
@@ -84,6 +84,10 @@
8484 logger.trace("Created connection pool to host {}", host);
8585 }
8686
87+ private PoolingOptions options() {
88+ return manager.configuration().getPoolingOptions();
89+ }
90+
8791 @Override
8892 public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
8993 if (isClosed())
@@ -100,7 +104,8 @@
100104 while (true) {
101105 int inFlight = connection.inFlight.get();
102106
103- if (inFlight >= connection.maxAvailableStreams()) {
107+ if (inFlight >= Math.min(connection.maxAvailableStreams(),
108+ options().getMaxSimultaneousRequestsPerHostThreshold(hostDistance))) {
104109 connection = waitForConnection(timeout, unit);
105110 break;
106111 }
@@ -172,7 +177,8 @@
172177 while (true) {
173178 int inFlight = connection.inFlight.get();
174179
175- if (inFlight >= connection.maxAvailableStreams())
180+ if (inFlight >= Math.min(connection.maxAvailableStreams(),
181+ options().getMaxSimultaneousRequestsPerHostThreshold(hostDistance)))
176182 break;
177183
178184 if (connection.inFlight.compareAndSet(inFlight, inFlight + 1))
modified driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java +2 −0
@@ -31,6 +31,8 @@
3131 * To minimize the average time to find that long, we search the array in a round-robin fashion.
3232 */
3333 class StreamIdGenerator {
34+ static final int MAX_STREAM_PER_CONNECTION_V2 = 128;
35+ static final int MAX_STREAM_PER_CONNECTION_V3 = 32768;
3436 private static final long MAX_UNSIGNED_LONG = -1L;
3537
3638 static StreamIdGenerator newInstance(ProtocolVersion version) {
added driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +53 −0
@@ -0,0 +1,53 @@
1+package com.datastax.driver.core;
2+
3+import java.net.InetSocketAddress;
4+import java.util.Collection;
5+import java.util.concurrent.Executors;
6+import java.util.concurrent.ScheduledExecutorService;
7+import java.util.concurrent.TimeUnit;
8+import java.util.concurrent.atomic.AtomicBoolean;
9+
10+import org.testng.annotations.Test;
11+import org.testng.collections.Lists;
12+
13+import static org.testng.Assert.fail;
14+
15+public class SingleConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
16+ @Override
17+ protected Collection<String> getTableDefinitions() {
18+ TestUtils.versionCheck(2.1, 0, "This will only work with Cassandra 2.1.0+");
19+
20+ return Lists.newArrayList();
21+ }
22+
23+ @Test(groups = "short")
24+ public void should_throttle_requests() {
25+ // Throttle to a very low value. Even a single thread can generate a higher throughput.
26+ final int maxRequests = 10;
27+ cluster.getConfiguration().getPoolingOptions()
28+ .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL, maxRequests);
29+
30+ // Track in flight requests in a dedicated thread every second
31+ final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
32+ final Host host = cluster.getMetadata().getHost(new InetSocketAddress(CCMBridge.IP_PREFIX + "1", 9042));
33+ ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
34+ final Runnable openConnectionsWatcher = new Runnable() {
35+ @Override
36+ public void run() {
37+ int inFlight = session.getState().getInFlightQueries(host);
38+ if (inFlight > maxRequests)
39+ excessInflightQueriesSpotted.set(true);
40+ }
41+ };
42+ openConnectionsWatcherExecutor.scheduleAtFixedRate(openConnectionsWatcher, 200, 200, TimeUnit.MILLISECONDS);
43+
44+ // Generate the load
45+ for (int i = 0; i < 10000; i++)
46+ session.executeAsync("SELECT release_version FROM system.local");
47+
48+ openConnectionsWatcherExecutor.shutdownNow();
49+ if (excessInflightQueriesSpotted.get()) {
50+ fail("Inflight queries exceeded the limit");
51+ }
52+ }
53+}