Elffuss BraidHub

kikocis/java-driver public

JAVA-1292: Adjusted frame length error breaks ability to read data (#748)

Also addresses JAVA-1293: Make DecoderForStreamId.MAX_FRAME_LENGTH
configurable by adding a SystemProperty
com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB which defaults
to 256.
Changeset205c5dd93f7f20180806dc380ef72ea6ae38f31b702cb46024fed3b768434294
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2016-09-18 14:44 -05:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-09-18 12:44 -07:00
Parents70bb916c4680

Browse the files at this changeset

6 files changed

modified changelog/README.md +2 −0
@@ -12,6 +12,8 @@
1212 - [bug] JAVA-1283: Don't cache failed query preparations in the mapper.
1313 - [improvement] JAVA-1277: Expose AbstractSession.checkNotInEventLoop.
1414 - [bug] JAVA-1272: BuiltStatement not able to print its query string if it contains mapped UDTs.
15+- [bug] JAVA-1292: 'Adjusted frame length' error breaks driver's ability to read data.
16+- [improvement] JAVA-1293: Make DecoderForStreamIdSize.MAX_FRAME_LENGTH configurable.
1517
1618
1719 ### 3.0.3
modified driver-core/pom.xml +1 −0
@@ -323,6 +323,7 @@
323323 <include>**/SSL*Test.java</include>
324324 <include>**/ControlConnectionTest.java</include>
325325 <include>**/ExtendedPeerCheckDisabledTest.java</include>
326+ <include>**/FrameLengthTest.java</include>
326327 </includes>
327328 </configuration>
328329 </plugin>
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +23 −1
@@ -27,6 +27,7 @@
2727 import io.netty.channel.group.ChannelGroup;
2828 import io.netty.channel.group.DefaultChannelGroup;
2929 import io.netty.channel.socket.SocketChannel;
30+import io.netty.handler.codec.DecoderException;
3031 import io.netty.handler.timeout.IdleStateEvent;
3132 import io.netty.handler.timeout.IdleStateHandler;
3233 import io.netty.util.Timeout;
@@ -993,7 +994,7 @@
993994 ResponseHandler handler = pending.remove(streamId);
994995 streamIdHandler.release(streamId);
995996 if (handler == null) {
996- /**
997+ /*
997998 * During normal operation, we should not receive responses for which we don't have a handler. There is
998999 * two cases however where this can happen:
9991000 * 1) The connection has been defuncted due to some internal error and we've raced between removing the
@@ -1046,6 +1047,27 @@
10461047 if (writer.get() > 0)
10471048 return;
10481049
1050+ if (cause instanceof DecoderException) {
1051+ Throwable error = cause.getCause();
1052+ // Special case, if we encountered a FrameTooLongException, raise exception on handler and don't defunct it since
1053+ // the connection is in an ok state.
1054+ if (error != null && error instanceof FrameTooLongException) {
1055+ FrameTooLongException ftle = (FrameTooLongException) error;
1056+ int streamId = ftle.getStreamId();
1057+ ResponseHandler handler = pending.remove(streamId);
1058+ streamIdHandler.release(streamId);
1059+ if (handler == null) {
1060+ streamIdHandler.unmark(streamId);
1061+ if (logger.isDebugEnabled())
1062+ logger.debug("{} FrameTooLongException received on stream {} but no handler set anymore (either the request has "
1063+ + "timed out or it was closed due to another error).", Connection.this, streamId);
1064+ return;
1065+ }
1066+ handler.cancelTimeout();
1067+ handler.callback.onException(Connection.this, ftle, System.nanoTime() - handler.startTime, handler.retryCount);
1068+ return;
1069+ }
1070+ }
10491071 defunct(new TransportException(address, String.format("Unexpected exception triggered (%s)", cause), cause));
10501072 }
10511073
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +28 −19
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.DriverInternalError;
19+import com.datastax.driver.core.exceptions.FrameTooLongException;
1920 import io.netty.buffer.ByteBuf;
2021 import io.netty.channel.ChannelHandler;
2122 import io.netty.channel.ChannelHandlerContext;
@@ -189,42 +190,44 @@
189190 }
190191
191192 static final class Decoder extends ByteToMessageDecoder {
192- static final DecoderForStreamIdSize decoderV1 = new DecoderForStreamIdSize(1);
193- static final DecoderForStreamIdSize decoderV3 = new DecoderForStreamIdSize(2);
193+ private DecoderForStreamIdSize decoder;
194194
195195 @Override
196196 protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
197197 if (buffer.readableBytes() < 1)
198198 return;
199199
200- int version = buffer.getByte(buffer.readerIndex());
201- // version first bit is the "direction" of the frame (request or response)
202- version = version & 0x7F;
200+ // Initialize sub decoder on first message. No synchronization needed as
201+ // decode is always called from same thread.
202+ if (decoder == null) {
203+ int version = buffer.getByte(buffer.readerIndex());
204+ // version first bit is the "direction" of the frame (request or response)
205+ version = version & 0x7F;
206+ decoder = new DecoderForStreamIdSize(version, version >= 3 ? 2 : 1);
207+ }
203208
204- DecoderForStreamIdSize decoder = (version >= 3) ? decoderV3 : decoderV1;
205209 Object frame = decoder.decode(ctx, buffer);
206210 if (frame != null)
207211 out.add(frame);
208212 }
209213
210214 static class DecoderForStreamIdSize extends LengthFieldBasedFrameDecoder {
211- private static final int MAX_FRAME_LENGTH = 256 * 1024 * 1024; // 256 MB
212- private final int opcodeOffset;
213-
214- DecoderForStreamIdSize(int streamIdSize) {
215+ // The maximum response frame length allowed. Note that C* does not currently restrict the length of its responses (CASSANDRA-12630).
216+ private static final int MAX_FRAME_LENGTH = SystemProperties.getInt("com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB", 256) * 1024 * 1024; // 256 MB
217+ private final int protocolVersion;
218+
219+ DecoderForStreamIdSize(int protocolVersion, int streamIdSize) {
215220 super(MAX_FRAME_LENGTH, /*lengthOffset=*/ 3 + streamIdSize, 4, 0, 0, true);
216- this.opcodeOffset = 2 + streamIdSize;
221+ this.protocolVersion = protocolVersion;
217222 }
218223
219224 @Override
220225 protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
226+ // Capture current index in case we need to get the stream id.
227+ // If a TooLongFrameException is thrown the readerIndex will advance to the end of
228+ // the buffer (or past the frame) so we need the position as we entered this method.
229+ int curIndex = buffer.readerIndex();
221230 try {
222- if (buffer.readableBytes() < opcodeOffset + 1)
223- return null;
224-
225- // Validate the opcode (this will throw if it's not a response)
226- Message.Response.Type.fromOpcode(buffer.getByte(buffer.readerIndex() + opcodeOffset));
227-
228231 ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
229232 if (frame == null) {
230233 return null;
@@ -232,11 +235,17 @@
232235 // Do not deallocate `frame` just yet, because it is stored as Frame.body and will be used
233236 // in Message.ProtocolDecoder or Frame.Decompressor if compression is enabled (we deallocate
234237 // it there).
235- return Frame.create(frame);
238+ Frame theFrame = Frame.create(frame);
239+ // Validate the opcode (this will throw if it's not a response)
240+ Message.Response.Type.fromOpcode(theFrame.header.opcode);
241+ return theFrame;
236242 } catch (CorruptedFrameException e) {
237243 throw new DriverInternalError(e);
238244 } catch (TooLongFrameException e) {
239- throw new DriverInternalError(e);
245+ int streamId = protocolVersion > 2 ?
246+ buffer.getShort(curIndex + 2) :
247+ buffer.getByte(curIndex + 2);
248+ throw new FrameTooLongException(streamId);
240249 }
241250 }
242251 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/FrameTooLongException.java +50 −0
@@ -0,0 +1,50 @@
1+/*
2+ * Copyright (C) 2012-2015 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.exceptions;
17+
18+/**
19+ * Indicates that the response frame for a request exceeded
20+ * {@link com.datastax.driver.core.Frame.Decoder.DecoderForStreamIdSize#MAX_FRAME_LENGTH}
21+ * (default: 256MB, configurable via com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB
22+ * system property) and thus was not parsed.
23+ */
24+public class FrameTooLongException extends DriverException {
25+
26+ private static final long serialVersionUID = 0;
27+
28+ private final int streamId;
29+
30+ public FrameTooLongException(int streamId) {
31+ this(streamId, null);
32+ }
33+
34+ private FrameTooLongException(int streamId, Throwable cause) {
35+ super("Response frame exceeded maximum allowed length", cause);
36+ this.streamId = streamId;
37+ }
38+
39+ /**
40+ * @return The stream id associated with the frame that caused this exception.
41+ */
42+ public int getStreamId() {
43+ return streamId;
44+ }
45+
46+ @Override
47+ public FrameTooLongException copy() {
48+ return new FrameTooLongException(streamId, this);
49+ }
50+}
added driver-core/src/test/java/com/datastax/driver/core/FrameLengthTest.java +121 −0
@@ -0,0 +1,121 @@
1+/*
2+ * Copyright (C) 2012-2015 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 com.datastax.driver.core.exceptions.FrameTooLongException;
19+import com.datastax.driver.core.querybuilder.Insert;
20+import com.datastax.driver.core.schemabuilder.Create;
21+import com.datastax.driver.core.schemabuilder.SchemaBuilder;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
24+import org.testng.annotations.BeforeClass;
25+import org.testng.annotations.Test;
26+
27+import java.nio.ByteBuffer;
28+import java.util.Collection;
29+import java.util.Random;
30+
31+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
32+import static org.assertj.core.api.Assertions.assertThat;
33+import static org.assertj.core.api.Fail.fail;
34+
35+@CCMConfig(numberOfNodes = 2)
36+public class FrameLengthTest extends CCMTestsSupport {
37+
38+ Logger logger = LoggerFactory.getLogger(FrameLengthTest.class);
39+
40+ private static final String tableName = "blob_table";
41+ private static final int colCount = 256;
42+ private static final int rowsPerPartitionCount = 4;
43+ private static final int partitionCount = 1;
44+ private static final int bytesPerCol = 1024;
45+
46+ @BeforeClass(groups = {"isolated"})
47+ public void beforeTestClass() throws Exception {
48+ // Set max frame size to 1MB to make it easier to manifest frame length error.
49+ System.setProperty("com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB", "1");
50+ super.beforeTestClass();
51+ }
52+
53+ @Override
54+ public void onTestContextInitialized() {
55+ logger.info("Creating table {} with {} {}-byte blob columns", tableName, colCount, bytesPerCol);
56+ Random random = new Random();
57+ // Create table
58+ Create create = SchemaBuilder.createTable(tableName).addPartitionKey("k", DataType.cint()).addClusteringColumn("c", DataType.cint());
59+ for (int i = 0; i < colCount; i++) {
60+ create.addColumn("col" + i, DataType.blob());
61+ }
62+ execute(create.getQueryString());
63+
64+ // build prepared statement.
65+ Insert insert = insertInto(tableName).value("k", bindMarker()).value("c", bindMarker());
66+ for (int i = 0; i < colCount; i++) {
67+ insert = insert.value("col" + i, bindMarker());
68+ }
69+
70+ PreparedStatement prepared = session().prepare(insert);
71+
72+ // Insert rows.
73+ logger.info("Inserting data for {} partitions.", partitionCount);
74+ for (int i = 0; i < partitionCount; i++) {
75+ logger.info("Inserting {} rows in partition {}", rowsPerPartitionCount, i);
76+ for (int r = 0; r < rowsPerPartitionCount; r++) {
77+ BoundStatement stmt = prepared.bind();
78+ stmt.setInt("k", i);
79+ stmt.setInt("c", r);
80+ for (int c = 0; c < colCount; c++) {
81+ byte[] b = new byte[bytesPerCol];
82+ random.nextBytes(b);
83+ ByteBuffer in = ByteBuffer.wrap(b);
84+ stmt.setBytes("col" + c, in);
85+ }
86+ session().execute(stmt);
87+ }
88+ }
89+ logger.info("Done loading {}", tableName);
90+ }
91+
92+ /**
93+ * Validates that if a frame is received that exceeds NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB that
94+ * the driver is able to recover, not lose host connectivity and make further queries. It
95+ * configures NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB to 1 MB to make the error easier to reproduce.
96+ *
97+ * @jira_ticket JAVA-1292
98+ * @jira_ticket JAVA-1293
99+ * @test_category connection
100+ */
101+ @Test(groups = "isolated")
102+ public void should_throw_exception_when_frame_exceeds_configured_max() {
103+ try {
104+ session().execute(select().from(tableName).where(eq("k", 0)));
105+ fail("Exception expected");
106+ } catch (FrameTooLongException ftle) {
107+ // Expected.
108+ }
109+
110+ // Both hosts should remain up.
111+ Collection<Host> hosts = session().getState().getConnectedHosts();
112+ assertThat(hosts).hasSize(2).extractingResultOf("isUp").containsOnly(true);
113+
114+ // Should be able to make a query that is less than the max frame size.
115+ // Execute multiple time to exercise all hosts.
116+ for (int i = 0; i < 10; i++) {
117+ ResultSet result = session().execute(select().from(tableName).where(eq("k", 0)).and(eq("c", 0)));
118+ assertThat(result.getAvailableWithoutFetching()).isEqualTo(1);
119+ }
120+ }
121+}