You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by bd...@apache.org on 2018/03/15 23:42:49 UTC
[1/5] cassandra git commit: Abstract streaming for pluggable storage
Repository: cassandra
Updated Branches:
refs/heads/trunk 253c003df -> 9714a7c81
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/streaming/async/StreamingInboundHandlerTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/async/StreamingInboundHandlerTest.java b/test/unit/org/apache/cassandra/streaming/async/StreamingInboundHandlerTest.java
index b4a736e..78a7879 100644
--- a/test/unit/org/apache/cassandra/streaming/async/StreamingInboundHandlerTest.java
+++ b/test/unit/org/apache/cassandra/streaming/async/StreamingInboundHandlerTest.java
@@ -20,7 +20,6 @@ package org.apache.cassandra.streaming.async;
import java.io.EOFException;
import java.io.IOException;
-import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.UUID;
@@ -46,8 +45,8 @@ import org.apache.cassandra.streaming.StreamResultFuture;
import org.apache.cassandra.streaming.StreamSession;
import org.apache.cassandra.streaming.async.StreamingInboundHandler.SessionIdentifier;
import org.apache.cassandra.streaming.messages.CompleteMessage;
-import org.apache.cassandra.streaming.messages.FileMessageHeader;
-import org.apache.cassandra.streaming.messages.IncomingFileMessage;
+import org.apache.cassandra.streaming.messages.StreamMessageHeader;
+import org.apache.cassandra.streaming.messages.IncomingStreamMessage;
import org.apache.cassandra.streaming.messages.StreamInitMessage;
import org.apache.cassandra.streaming.messages.StreamMessage;
@@ -125,7 +124,7 @@ public class StreamingInboundHandlerTest
@Test
public void StreamDeserializingTask_deriveSession_StreamInitMessage() throws InterruptedException, IOException
{
- StreamInitMessage msg = new StreamInitMessage(REMOTE_ADDR, 0, UUID.randomUUID(), StreamOperation.REPAIR, true, UUID.randomUUID(), PreviewKind.ALL);
+ StreamInitMessage msg = new StreamInitMessage(REMOTE_ADDR, 0, UUID.randomUUID(), StreamOperation.REPAIR, UUID.randomUUID(), PreviewKind.ALL);
StreamingInboundHandler.StreamDeserializingTask task = handler.new StreamDeserializingTask(sid -> createSession(sid), null, channel);
StreamSession session = task.deriveSession(msg);
Assert.assertNotNull(session);
@@ -133,7 +132,7 @@ public class StreamingInboundHandlerTest
private StreamSession createSession(SessionIdentifier sid)
{
- return new StreamSession(sid.from, sid.from, (connectionId, protocolVersion) -> null, sid.sessionIndex, true, UUID.randomUUID(), PreviewKind.ALL);
+ return new StreamSession(StreamOperation.BOOTSTRAP, sid.from, sid.from, (connectionId, protocolVersion) -> null, sid.sessionIndex, UUID.randomUUID(), PreviewKind.ALL);
}
@Test (expected = IllegalStateException.class)
@@ -147,9 +146,9 @@ public class StreamingInboundHandlerTest
@Test (expected = IllegalStateException.class)
public void StreamDeserializingTask_deriveSession_IFM_NoSession() throws InterruptedException, IOException
{
- FileMessageHeader header = new FileMessageHeader(TableId.generate(), REMOTE_ADDR, UUID.randomUUID(), 0, 0,
- BigFormat.latestVersion, SSTableFormat.Type.BIG, 0, new ArrayList<>(), null, 0, UUID.randomUUID(), 0 , null);
- IncomingFileMessage msg = new IncomingFileMessage(null, header);
+ StreamMessageHeader header = new StreamMessageHeader(TableId.generate(), REMOTE_ADDR, UUID.randomUUID(),
+ 0, 0, 0, UUID.randomUUID());
+ IncomingStreamMessage msg = new IncomingStreamMessage(null, header);
StreamingInboundHandler.StreamDeserializingTask task = handler.new StreamDeserializingTask(sid -> StreamManager.instance.findSession(sid.from, sid.planId, sid.sessionIndex), null, channel);
task.deriveSession(msg);
}
@@ -158,11 +157,11 @@ public class StreamingInboundHandlerTest
public void StreamDeserializingTask_deriveSession_IFM_HasSession() throws InterruptedException, IOException
{
UUID planId = UUID.randomUUID();
- StreamResultFuture future = StreamResultFuture.initReceivingSide(0, planId, StreamOperation.REPAIR, REMOTE_ADDR, channel, true, UUID.randomUUID(), PreviewKind.ALL);
+ StreamResultFuture future = StreamResultFuture.initReceivingSide(0, planId, StreamOperation.REPAIR, REMOTE_ADDR, channel, UUID.randomUUID(), PreviewKind.ALL);
StreamManager.instance.register(future);
- FileMessageHeader header = new FileMessageHeader(TableId.generate(), REMOTE_ADDR, planId, 0, 0,
- BigFormat.latestVersion, SSTableFormat.Type.BIG, 0, new ArrayList<>(), null, 0, UUID.randomUUID(), 0 , null);
- IncomingFileMessage msg = new IncomingFileMessage(null, header);
+ StreamMessageHeader header = new StreamMessageHeader(TableId.generate(), REMOTE_ADDR, planId, 0,
+ 0, 0, UUID.randomUUID());
+ IncomingStreamMessage msg = new IncomingStreamMessage(null, header);
StreamingInboundHandler.StreamDeserializingTask task = handler.new StreamDeserializingTask(sid -> StreamManager.instance.findSession(sid.from, sid.planId, sid.sessionIndex), null, channel);
StreamSession session = task.deriveSession(msg);
Assert.assertNotNull(session);
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/streaming/compression/CompressedInputStreamTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/compression/CompressedInputStreamTest.java b/test/unit/org/apache/cassandra/streaming/compression/CompressedInputStreamTest.java
index 16b3a76..60d8b6c 100644
--- a/test/unit/org/apache/cassandra/streaming/compression/CompressedInputStreamTest.java
+++ b/test/unit/org/apache/cassandra/streaming/compression/CompressedInputStreamTest.java
@@ -34,8 +34,8 @@ import org.apache.cassandra.schema.CompressionParams;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
-import org.apache.cassandra.streaming.compress.CompressedInputStream;
-import org.apache.cassandra.streaming.compress.CompressionInfo;
+import org.apache.cassandra.db.streaming.CompressedInputStream;
+import org.apache.cassandra.db.streaming.CompressionInfo;
import org.apache.cassandra.utils.ChecksumType;
import org.apache.cassandra.utils.Pair;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
[5/5] cassandra git commit: Abstract streaming for pluggable storage
Posted by bd...@apache.org.
Abstract streaming for pluggable storage
Patch by Blake Eggleston; Reviewed by Jason Brown for CASSANDRA-14115
Project: http://git-wip-us.apache.org/repos/asf/cassandra/repo
Commit: http://git-wip-us.apache.org/repos/asf/cassandra/commit/9714a7c8
Tree: http://git-wip-us.apache.org/repos/asf/cassandra/tree/9714a7c8
Diff: http://git-wip-us.apache.org/repos/asf/cassandra/diff/9714a7c8
Branch: refs/heads/trunk
Commit: 9714a7c817b64a3358f69e536535c756c5c6df48
Parents: 253c003
Author: Blake Eggleston <bd...@gmail.com>
Authored: Sun Mar 4 14:44:30 2018 -0800
Committer: Blake Eggleston <bd...@gmail.com>
Committed: Thu Mar 15 16:40:05 2018 -0700
----------------------------------------------------------------------
CHANGES.txt | 1 +
.../apache/cassandra/db/ColumnFamilyStore.java | 10 +
.../db/streaming/CassandraIncomingFile.java | 117 +++++++
.../db/streaming/CassandraOutgoingFile.java | 151 +++++++++
.../db/streaming/CassandraStreamHeader.java | 212 +++++++++++++
.../db/streaming/CassandraStreamManager.java | 166 ++++++++++
.../db/streaming/CassandraStreamReader.java | 285 +++++++++++++++++
.../db/streaming/CassandraStreamReceiver.java | 248 +++++++++++++++
.../db/streaming/CassandraStreamWriter.java | 176 +++++++++++
.../CompressedCassandraStreamReader.java | 131 ++++++++
.../CompressedCassandraStreamWriter.java | 153 ++++++++++
.../db/streaming/CompressedInputStream.java | 285 +++++++++++++++++
.../cassandra/db/streaming/CompressionInfo.java | 110 +++++++
.../cassandra/db/streaming/package-info.java | 53 ++++
.../org/apache/cassandra/dht/RangeStreamer.java | 4 +-
.../cassandra/io/sstable/SSTableLoader.java | 18 +-
.../repair/AsymmetricLocalSyncTask.java | 1 -
.../apache/cassandra/repair/LocalSyncTask.java | 2 +-
.../cassandra/repair/StreamingRepairTask.java | 2 +-
.../cassandra/streaming/IncomingStream.java | 45 +++
.../cassandra/streaming/OutgoingStream.java | 52 ++++
.../apache/cassandra/streaming/PreviewKind.java | 21 +-
.../cassandra/streaming/ProgressInfo.java | 4 +-
.../apache/cassandra/streaming/SessionInfo.java | 8 +-
.../cassandra/streaming/StreamCoordinator.java | 40 ++-
.../apache/cassandra/streaming/StreamHook.java | 14 +-
.../apache/cassandra/streaming/StreamPlan.java | 20 +-
.../cassandra/streaming/StreamReader.java | 278 -----------------
.../cassandra/streaming/StreamReceiveTask.java | 211 ++-----------
.../cassandra/streaming/StreamReceiver.java | 58 ++++
.../cassandra/streaming/StreamResultFuture.java | 7 +-
.../cassandra/streaming/StreamSession.java | 199 ++++--------
.../cassandra/streaming/StreamTransferTask.java | 58 ++--
.../cassandra/streaming/StreamWriter.java | 173 -----------
.../cassandra/streaming/TableStreamManager.java | 57 ++++
.../async/NettyStreamingMessageSender.java | 41 ++-
.../async/StreamingInboundHandler.java | 23 +-
.../cassandra/streaming/async/package-info.java | 36 +--
.../compress/CompressedInputStream.java | 285 -----------------
.../compress/CompressedStreamReader.java | 132 --------
.../compress/CompressedStreamWriter.java | 154 ----------
.../streaming/compress/CompressionInfo.java | 95 ------
.../management/ProgressInfoCompositeData.java | 2 +-
.../streaming/messages/FileMessageHeader.java | 304 -------------------
.../streaming/messages/IncomingFileMessage.java | 95 ------
.../messages/IncomingStreamMessage.java | 107 +++++++
.../streaming/messages/OutgoingFileMessage.java | 158 ----------
.../messages/OutgoingStreamMessage.java | 138 +++++++++
.../streaming/messages/StreamInitMessage.java | 9 +-
.../streaming/messages/StreamMessage.java | 2 +-
.../streaming/messages/StreamMessageHeader.java | 144 +++++++++
.../db/streaming/CassandraStreamHeaderTest.java | 50 +++
.../streaming/CassandraStreamManagerTest.java | 237 +++++++++++++++
.../cassandra/dht/StreamStateStoreTest.java | 5 +-
.../cassandra/io/sstable/LegacySSTableTest.java | 14 +-
.../io/sstable/SSTableRewriterTest.java | 59 ----
.../serializers/SerializationUtils.java | 68 +++++
.../cassandra/streaming/StreamSessionTest.java | 132 --------
.../streaming/StreamTransferTaskTest.java | 19 +-
.../streaming/StreamingTransferTest.java | 27 +-
.../async/NettyStreamingMessageSenderTest.java | 5 +-
.../async/StreamingInboundHandlerTest.java | 23 +-
.../compression/CompressedInputStreamTest.java | 4 +-
63 files changed, 3314 insertions(+), 2424 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/CHANGES.txt
----------------------------------------------------------------------
diff --git a/CHANGES.txt b/CHANGES.txt
index 42add69..9458f19 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,4 +1,5 @@
4.0
+ * Abstract streaming for pluggable storage (CASSANDRA-14115)
* Forced incremental repairs should promote sstables if they can (CASSANDRA-14294)
* Use Murmur3 for validation compactions (CASSANDRA-14002)
* Comma at the end of the seed list is interpretated as localhost (CASSANDRA-14285)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/ColumnFamilyStore.java b/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
index 007bf2d..1be0083 100644
--- a/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
+++ b/src/java/org/apache/cassandra/db/ColumnFamilyStore.java
@@ -50,6 +50,7 @@ import org.apache.cassandra.db.commitlog.CommitLogPosition;
import org.apache.cassandra.db.compaction.*;
import org.apache.cassandra.db.filter.ClusteringIndexFilter;
import org.apache.cassandra.db.filter.DataLimits;
+import org.apache.cassandra.db.streaming.CassandraStreamManager;
import org.apache.cassandra.db.view.TableViews;
import org.apache.cassandra.db.lifecycle.*;
import org.apache.cassandra.db.partitions.CachedPartition;
@@ -78,6 +79,7 @@ import org.apache.cassandra.schema.*;
import org.apache.cassandra.schema.CompactionParams.TombstoneOption;
import org.apache.cassandra.service.CacheService;
import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.streaming.TableStreamManager;
import org.apache.cassandra.utils.*;
import org.apache.cassandra.utils.TopKSampler.SamplerResult;
import org.apache.cassandra.utils.concurrent.OpOrder;
@@ -213,6 +215,8 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean
public volatile long sampleLatencyNanos;
private final ScheduledFuture<?> latencyCalculator;
+ private final CassandraStreamManager streamManager;
+
private volatile boolean compactionSpaceCheck = true;
@VisibleForTesting
@@ -465,6 +469,12 @@ public class ColumnFamilyStore implements ColumnFamilyStoreMBean
mbeanName = null;
oldMBeanName= null;
}
+ streamManager = new CassandraStreamManager(this);
+ }
+
+ public TableStreamManager getStreamManager()
+ {
+ return streamManager;
}
public TableMetadata metadata()
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CassandraIncomingFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CassandraIncomingFile.java b/src/java/org/apache/cassandra/db/streaming/CassandraIncomingFile.java
new file mode 100644
index 0000000..16698e5
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CassandraIncomingFile.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db.streaming;
+
+import java.io.IOException;
+import java.util.Objects;
+
+import com.google.common.base.Preconditions;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.io.sstable.SSTableMultiWriter;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.streaming.IncomingStream;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.streaming.messages.StreamMessageHeader;
+
+/**
+ * used to receive the part(or whole) of a SSTable data file.
+ *
+ * This class deserializes the data stream into partitions and rows, and writes that out as an sstable
+ */
+public class CassandraIncomingFile implements IncomingStream
+{
+ private final ColumnFamilyStore cfs;
+ private final StreamSession session;
+ private final StreamMessageHeader header;
+
+ private volatile SSTableMultiWriter sstable;
+ private volatile long size = -1;
+
+ public CassandraIncomingFile(ColumnFamilyStore cfs, StreamSession session, StreamMessageHeader header)
+ {
+ this.cfs = cfs;
+ this.session = session;
+ this.header = header;
+ }
+
+ @Override
+ public synchronized void read(DataInputPlus in, int version) throws IOException
+ {
+ CassandraStreamHeader streamHeader = CassandraStreamHeader.serializer.deserialize(in, version);
+ CassandraStreamReader reader = !streamHeader.isCompressed()
+ ? new CassandraStreamReader(header, streamHeader, session)
+ : new CompressedCassandraStreamReader(header, streamHeader, session);
+ size = streamHeader.size();
+ sstable = reader.read(in);
+ }
+
+ @Override
+ public synchronized String getName()
+ {
+ return sstable == null ? "null" : sstable.getFilename();
+ }
+
+ @Override
+ public synchronized long getSize()
+ {
+ Preconditions.checkState(size > 0, "Stream hasn't been read yet");
+ return size;
+ }
+
+ @Override
+ public TableId getTableId()
+ {
+ Preconditions.checkState(sstable != null, "Stream hasn't been read yet");
+ return sstable.getTableId();
+ }
+
+ @Override
+ public String toString()
+ {
+ SSTableMultiWriter sst = sstable;
+ return "CassandraIncomingFile{" +
+ "sstable=" + (sst == null ? "null" : sst.getFilename()) +
+ '}';
+ }
+
+ public SSTableMultiWriter getSSTable()
+ {
+ Preconditions.checkState(sstable != null, "Stream hasn't been read yet");
+ return sstable;
+ }
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CassandraIncomingFile that = (CassandraIncomingFile) o;
+ return Objects.equals(cfs, that.cfs) &&
+ Objects.equals(session, that.session) &&
+ Objects.equals(header, that.header) &&
+ Objects.equals(sstable, that.sstable);
+ }
+
+ public int hashCode()
+ {
+
+ return Objects.hash(cfs, session, header, sstable);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CassandraOutgoingFile.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CassandraOutgoingFile.java b/src/java/org/apache/cassandra/db/streaming/CassandraOutgoingFile.java
new file mode 100644
index 0000000..3fd3f9d
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CassandraOutgoingFile.java
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db.streaming;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.io.util.DataOutputStreamPlus;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.streaming.OutgoingStream;
+import org.apache.cassandra.streaming.StreamOperation;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.concurrent.Ref;
+
+/**
+ * used to transfer the part(or whole) of a SSTable data file
+ */
+public class CassandraOutgoingFile implements OutgoingStream
+{
+ private final Ref<SSTableReader> ref;
+ private final long estimatedKeys;
+ private final List<Pair<Long, Long>> sections;
+ private final String filename;
+ private final CassandraStreamHeader header;
+ private final boolean keepSSTableLevel;
+
+ public CassandraOutgoingFile(StreamOperation operation, Ref<SSTableReader> ref, List<Pair<Long, Long>> sections, long estimatedKeys)
+ {
+ Preconditions.checkNotNull(ref.get());
+ this.ref = ref;
+ this.estimatedKeys = estimatedKeys;
+ this.sections = sections;
+ this.filename = ref.get().getFilename();
+
+ SSTableReader sstable = ref.get();
+ keepSSTableLevel = operation == StreamOperation.BOOTSTRAP || operation == StreamOperation.REBUILD;
+ this.header = new CassandraStreamHeader(sstable.descriptor.version,
+ sstable.descriptor.formatType,
+ estimatedKeys,
+ sections,
+ sstable.compression ? sstable.getCompressionMetadata() : null,
+ keepSSTableLevel ? sstable.getSSTableLevel() : 0,
+ sstable.header.toComponent());
+ }
+
+ public static CassandraOutgoingFile fromStream(OutgoingStream stream)
+ {
+ Preconditions.checkArgument(stream instanceof CassandraOutgoingFile);
+ return (CassandraOutgoingFile) stream;
+ }
+
+ @VisibleForTesting
+ public Ref<SSTableReader> getRef()
+ {
+ return ref;
+ }
+
+ @Override
+ public String getName()
+ {
+ return filename;
+ }
+
+ @Override
+ public long getSize()
+ {
+ return header.size();
+ }
+
+ @Override
+ public TableId getTableId()
+ {
+ return ref.get().metadata().id;
+ }
+
+ @Override
+ public long getRepairedAt()
+ {
+ return ref.get().getRepairedAt();
+ }
+
+ @Override
+ public UUID getPendingRepair()
+ {
+ return ref.get().getPendingRepair();
+ }
+
+ @Override
+ public void write(StreamSession session, DataOutputStreamPlus out, int version) throws IOException
+ {
+ SSTableReader sstable = ref.get();
+ CassandraStreamHeader.serializer.serialize(header, out, version);
+ out.flush();
+
+ CassandraStreamWriter writer = header.compressionInfo == null ?
+ new CassandraStreamWriter(sstable, header.sections, session) :
+ new CompressedCassandraStreamWriter(sstable, header.sections,
+ header.compressionInfo, session);
+ writer.write(out);
+ }
+
+ @Override
+ public void finish()
+ {
+ ref.release();
+ }
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CassandraOutgoingFile that = (CassandraOutgoingFile) o;
+ return estimatedKeys == that.estimatedKeys &&
+ Objects.equals(ref, that.ref) &&
+ Objects.equals(sections, that.sections);
+ }
+
+ public int hashCode()
+ {
+ return Objects.hash(ref, estimatedKeys, sections);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "CassandraOutgoingFile{" + ref.get().getFilename() + '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CassandraStreamHeader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CassandraStreamHeader.java b/src/java/org/apache/cassandra/db/streaming/CassandraStreamHeader.java
new file mode 100644
index 0000000..2603da1
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CassandraStreamHeader.java
@@ -0,0 +1,212 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db.streaming;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import org.apache.cassandra.db.SerializationHeader;
+import org.apache.cassandra.db.TypeSizes;
+import org.apache.cassandra.io.IVersionedSerializer;
+import org.apache.cassandra.io.compress.CompressionMetadata;
+import org.apache.cassandra.io.sstable.format.SSTableFormat;
+import org.apache.cassandra.io.sstable.format.Version;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.DataOutputPlus;
+import org.apache.cassandra.utils.Pair;
+
+public class CassandraStreamHeader
+{
+ /** SSTable version */
+ public final Version version;
+
+ /** SSTable format **/
+ public final SSTableFormat.Type format;
+ public final long estimatedKeys;
+ public final List<Pair<Long, Long>> sections;
+ /**
+ * Compression info for SSTable to send. Can be null if SSTable is not compressed.
+ * On sender, this field is always null to avoid holding large number of Chunks.
+ * Use compressionMetadata instead.
+ */
+ private final CompressionMetadata compressionMetadata;
+ public volatile CompressionInfo compressionInfo;
+ public final int sstableLevel;
+ public final SerializationHeader.Component header;
+
+ /* cached size value */
+ private transient final long size;
+
+ private CassandraStreamHeader(Version version, SSTableFormat.Type format, long estimatedKeys, List<Pair<Long, Long>> sections, CompressionMetadata compressionMetadata, CompressionInfo compressionInfo, int sstableLevel, SerializationHeader.Component header)
+ {
+ this.version = version;
+ this.format = format;
+ this.estimatedKeys = estimatedKeys;
+ this.sections = sections;
+ this.compressionMetadata = compressionMetadata;
+ this.compressionInfo = compressionInfo;
+ this.sstableLevel = sstableLevel;
+ this.header = header;
+
+ this.size = calculateSize();
+ }
+
+ public CassandraStreamHeader(Version version, SSTableFormat.Type format, long estimatedKeys, List<Pair<Long, Long>> sections, CompressionMetadata compressionMetadata, int sstableLevel, SerializationHeader.Component header)
+ {
+ this(version, format, estimatedKeys, sections, compressionMetadata, null, sstableLevel, header);
+ }
+
+ public CassandraStreamHeader(Version version, SSTableFormat.Type format, long estimatedKeys, List<Pair<Long, Long>> sections, CompressionInfo compressionInfo, int sstableLevel, SerializationHeader.Component header)
+ {
+ this(version, format, estimatedKeys, sections, null, compressionInfo, sstableLevel, header);
+ }
+
+ public boolean isCompressed()
+ {
+ return compressionInfo != null;
+ }
+
+ /**
+ * @return total file size to transfer in bytes
+ */
+ public long size()
+ {
+ return size;
+ }
+
+ private long calculateSize()
+ {
+ long transferSize = 0;
+ if (compressionInfo != null)
+ {
+ // calculate total length of transferring chunks
+ for (CompressionMetadata.Chunk chunk : compressionInfo.chunks)
+ transferSize += chunk.length + 4; // 4 bytes for CRC
+ }
+ else
+ {
+ for (Pair<Long, Long> section : sections)
+ transferSize += section.right - section.left;
+ }
+ return transferSize;
+ }
+
+ public synchronized void calculateCompressionInfo()
+ {
+ if (compressionMetadata != null && compressionInfo == null)
+ {
+ compressionInfo = CompressionInfo.fromCompressionMetadata(compressionMetadata, sections);
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return "CassandraStreamHeader{" +
+ "version=" + version +
+ ", format=" + format +
+ ", estimatedKeys=" + estimatedKeys +
+ ", sections=" + sections +
+ ", compressionInfo=" + compressionInfo +
+ ", sstableLevel=" + sstableLevel +
+ ", header=" + header +
+ '}';
+ }
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ CassandraStreamHeader that = (CassandraStreamHeader) o;
+ return estimatedKeys == that.estimatedKeys &&
+ sstableLevel == that.sstableLevel &&
+ Objects.equals(version, that.version) &&
+ format == that.format &&
+ Objects.equals(sections, that.sections) &&
+ Objects.equals(compressionInfo, that.compressionInfo) &&
+ Objects.equals(header, that.header);
+ }
+
+ public int hashCode()
+ {
+ return Objects.hash(version, format, estimatedKeys, sections, compressionInfo, sstableLevel, header);
+ }
+
+
+ public static final IVersionedSerializer<CassandraStreamHeader> serializer = new IVersionedSerializer<CassandraStreamHeader>()
+ {
+ public void serialize(CassandraStreamHeader header, DataOutputPlus out, int version) throws IOException
+ {
+ out.writeUTF(header.version.toString());
+ out.writeUTF(header.format.name);
+
+ out.writeLong(header.estimatedKeys);
+ out.writeInt(header.sections.size());
+ for (Pair<Long, Long> section : header.sections)
+ {
+ out.writeLong(section.left);
+ out.writeLong(section.right);
+ }
+ header.calculateCompressionInfo();
+ CompressionInfo.serializer.serialize(header.compressionInfo, out, version);
+ out.writeInt(header.sstableLevel);
+ SerializationHeader.serializer.serialize(header.version, header.header, out);
+ }
+
+ public CassandraStreamHeader deserialize(DataInputPlus in, int version) throws IOException
+ {
+ Version sstableVersion = SSTableFormat.Type.current().info.getVersion(in.readUTF());
+ SSTableFormat.Type format = SSTableFormat.Type.validate(in.readUTF());
+
+ long estimatedKeys = in.readLong();
+ int count = in.readInt();
+ List<Pair<Long, Long>> sections = new ArrayList<>(count);
+ for (int k = 0; k < count; k++)
+ sections.add(Pair.create(in.readLong(), in.readLong()));
+ CompressionInfo compressionInfo = CompressionInfo.serializer.deserialize(in, version);
+ int sstableLevel = in.readInt();
+ SerializationHeader.Component header = SerializationHeader.serializer.deserialize(sstableVersion, in);
+
+ return new CassandraStreamHeader(sstableVersion, format, estimatedKeys, sections, compressionInfo, sstableLevel, header);
+ }
+
+ public long serializedSize(CassandraStreamHeader header, int version)
+ {
+ long size = 0;
+ size += TypeSizes.sizeof(header.version.toString());
+ size += TypeSizes.sizeof(header.format.name);
+ size += TypeSizes.sizeof(header.estimatedKeys);
+
+ size += TypeSizes.sizeof(header.sections.size());
+ for (Pair<Long, Long> section : header.sections)
+ {
+ size += TypeSizes.sizeof(section.left);
+ size += TypeSizes.sizeof(section.right);
+ }
+ size += CompressionInfo.serializer.serializedSize(header.compressionInfo, version);
+ size += TypeSizes.sizeof(header.sstableLevel);
+
+ size += SerializationHeader.serializer.serializedSize(header.version, header.header);
+
+ return size;
+ }
+ };
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CassandraStreamManager.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CassandraStreamManager.java b/src/java/org/apache/cassandra/db/streaming/CassandraStreamManager.java
new file mode 100644
index 0000000..466fa36
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CassandraStreamManager.java
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db.streaming;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.PartitionPosition;
+import org.apache.cassandra.db.lifecycle.SSTableIntervalTree;
+import org.apache.cassandra.db.lifecycle.SSTableSet;
+import org.apache.cassandra.db.lifecycle.View;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.streaming.IncomingStream;
+import org.apache.cassandra.streaming.OutgoingStream;
+import org.apache.cassandra.streaming.PreviewKind;
+import org.apache.cassandra.streaming.StreamReceiver;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.streaming.TableStreamManager;
+import org.apache.cassandra.streaming.messages.StreamMessageHeader;
+import org.apache.cassandra.utils.Pair;
+import org.apache.cassandra.utils.concurrent.Ref;
+import org.apache.cassandra.utils.concurrent.Refs;
+
+/**
+ * Implements the streaming interface for the native cassandra storage engine.
+ *
+ * Handles the streaming a one or more section of one of more sstables to and from a specific
+ * remote node. The sending side performs a block-level transfer of the source stream, while the receiver
+ * must deserilaize that data stream into an partitions and rows, and then write that out as an sstable.
+ */
+public class CassandraStreamManager implements TableStreamManager
+{
+ private static final Logger logger = LoggerFactory.getLogger(CassandraStreamManager.class);
+
+ private final ColumnFamilyStore cfs;
+
+ public CassandraStreamManager(ColumnFamilyStore cfs)
+ {
+ this.cfs = cfs;
+ }
+
+ @Override
+ public IncomingStream prepareIncomingStream(StreamSession session, StreamMessageHeader header)
+ {
+ return new CassandraIncomingFile(cfs, session, header);
+ }
+
+ @Override
+ public StreamReceiver createStreamReceiver(StreamSession session, int totalStreams)
+ {
+ return new CassandraStreamReceiver(cfs, session, totalStreams);
+ }
+
+ private static Predicate<SSTableReader> getPreviewPredicate(PreviewKind kind)
+ {
+ switch (kind)
+ {
+ case ALL:
+ return Predicates.alwaysTrue();
+ case UNREPAIRED:
+ return Predicates.not(SSTableReader::isRepaired);
+ case REPAIRED:
+ return SSTableReader::isRepaired;
+ default:
+ throw new IllegalArgumentException("Unsupported kind: " + kind);
+ }
+ }
+
+ @Override
+ public Collection<OutgoingStream> createOutgoingStreams(StreamSession session, Collection<Range<Token>> ranges, UUID pendingRepair, PreviewKind previewKind)
+ {
+ Refs<SSTableReader> refs = new Refs<>();
+ try
+ {
+ final List<Range<PartitionPosition>> keyRanges = new ArrayList<>(ranges.size());
+ for (Range<Token> range : ranges)
+ keyRanges.add(Range.makeRowRange(range));
+ refs.addAll(cfs.selectAndReference(view -> {
+ Set<SSTableReader> sstables = Sets.newHashSet();
+ SSTableIntervalTree intervalTree = SSTableIntervalTree.build(view.select(SSTableSet.CANONICAL));
+ Predicate<SSTableReader> predicate;
+ if (previewKind.isPreview())
+ {
+ predicate = getPreviewPredicate(previewKind);
+ }
+ else if (pendingRepair == ActiveRepairService.NO_PENDING_REPAIR)
+ {
+ predicate = Predicates.alwaysTrue();
+ }
+ else
+ {
+ predicate = s -> s.isPendingRepair() && s.getSSTableMetadata().pendingRepair.equals(pendingRepair);
+ }
+
+ for (Range<PartitionPosition> keyRange : keyRanges)
+ {
+ // keyRange excludes its start, while sstableInBounds is inclusive (of both start and end).
+ // This is fine however, because keyRange has been created from a token range through Range.makeRowRange (see above).
+ // And that later method uses the Token.maxKeyBound() method to creates the range, which return a "fake" key that
+ // sort after all keys having the token. That "fake" key cannot however be equal to any real key, so that even
+ // including keyRange.left will still exclude any key having the token of the original token range, and so we're
+ // still actually selecting what we wanted.
+ for (SSTableReader sstable : Iterables.filter(View.sstablesInBounds(keyRange.left, keyRange.right, intervalTree), predicate))
+ {
+ sstables.add(sstable);
+ }
+ }
+
+ if (logger.isDebugEnabled())
+ logger.debug("ViewFilter for {}/{} sstables", sstables.size(), Iterables.size(view.select(SSTableSet.CANONICAL)));
+ return sstables;
+ }).refs);
+
+
+ List<OutgoingStream> streams = new ArrayList<>(refs.size());
+ for (SSTableReader sstable: refs)
+ {
+ Ref<SSTableReader> ref = refs.get(sstable);
+ List<Pair<Long, Long>> sections = sstable.getPositionsForRanges(ranges);
+ if (sections.isEmpty())
+ {
+ ref.release();
+ continue;
+ }
+ streams.add(new CassandraOutgoingFile(session.getStreamOperation(), ref, sections, sstable.estimatedKeysForRanges(ranges)));
+ }
+
+ return streams;
+ }
+ catch (Throwable t)
+ {
+ refs.release();
+ throw t;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CassandraStreamReader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CassandraStreamReader.java b/src/java/org/apache/cassandra/db/streaming/CassandraStreamReader.java
new file mode 100644
index 0000000..26ef5ed
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CassandraStreamReader.java
@@ -0,0 +1,285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.streaming;
+
+import java.io.*;
+import java.util.Collection;
+import java.util.UUID;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.UnmodifiableIterator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.io.util.TrackedDataInputPlus;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.db.*;
+import org.apache.cassandra.db.rows.*;
+import org.apache.cassandra.io.sstable.SSTableMultiWriter;
+import org.apache.cassandra.io.sstable.SSTableSimpleIterator;
+import org.apache.cassandra.io.sstable.format.RangeAwareSSTableWriter;
+import org.apache.cassandra.io.sstable.format.SSTableFormat;
+import org.apache.cassandra.io.sstable.format.Version;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.streaming.ProgressInfo;
+import org.apache.cassandra.streaming.StreamReceiver;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.streaming.compress.StreamCompressionInputStream;
+import org.apache.cassandra.streaming.messages.StreamMessageHeader;
+import org.apache.cassandra.streaming.messages.StreamMessage;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.Pair;
+
+/**
+ * CassandraStreamReader reads from stream and writes to SSTable.
+ */
+public class CassandraStreamReader
+{
+ private static final Logger logger = LoggerFactory.getLogger(CassandraStreamReader.class);
+ protected final TableId tableId;
+ protected final long estimatedKeys;
+ protected final Collection<Pair<Long, Long>> sections;
+ protected final StreamSession session;
+ protected final Version inputVersion;
+ protected final long repairedAt;
+ protected final UUID pendingRepair;
+ protected final SSTableFormat.Type format;
+ protected final int sstableLevel;
+ protected final SerializationHeader.Component header;
+ protected final int fileSeqNum;
+
+ public CassandraStreamReader(StreamMessageHeader header, CassandraStreamHeader streamHeader, StreamSession session)
+ {
+ if (session.getPendingRepair() != null)
+ {
+ // we should only ever be streaming pending repair
+ // sstables if the session has a pending repair id
+ assert session.getPendingRepair().equals(header.pendingRepair);
+ }
+ this.session = session;
+ this.tableId = header.tableId;
+ this.estimatedKeys = streamHeader.estimatedKeys;
+ this.sections = streamHeader.sections;
+ this.inputVersion = streamHeader.version;
+ this.repairedAt = header.repairedAt;
+ this.pendingRepair = header.pendingRepair;
+ this.format = streamHeader.format;
+ this.sstableLevel = streamHeader.sstableLevel;
+ this.header = streamHeader.header;
+ this.fileSeqNum = header.sequenceNumber;
+ }
+
+ /**
+ * @param inputPlus where this reads data from
+ * @return SSTable transferred
+ * @throws IOException if reading the remote sstable fails. Will throw an RTE if local write fails.
+ */
+ @SuppressWarnings("resource") // input needs to remain open, streams on top of it can't be closed
+ public SSTableMultiWriter read(DataInputPlus inputPlus) throws IOException
+ {
+ long totalSize = totalSize();
+
+ ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(tableId);
+ if (cfs == null)
+ {
+ // schema was dropped during streaming
+ throw new IOException("CF " + tableId + " was dropped during streaming");
+ }
+
+ logger.debug("[Stream #{}] Start receiving file #{} from {}, repairedAt = {}, size = {}, ks = '{}', table = '{}', pendingRepair = '{}'.",
+ session.planId(), fileSeqNum, session.peer, repairedAt, totalSize, cfs.keyspace.getName(),
+ cfs.getTableName(), pendingRepair);
+
+ StreamDeserializer deserializer = null;
+ SSTableMultiWriter writer = null;
+ try (StreamCompressionInputStream streamCompressionInputStream = new StreamCompressionInputStream(inputPlus, StreamMessage.CURRENT_VERSION))
+ {
+ TrackedDataInputPlus in = new TrackedDataInputPlus(streamCompressionInputStream);
+ deserializer = new StreamDeserializer(cfs.metadata(), in, inputVersion, getHeader(cfs.metadata()));
+ writer = createWriter(cfs, totalSize, repairedAt, pendingRepair, format);
+ while (in.getBytesRead() < totalSize)
+ {
+ writePartition(deserializer, writer);
+ // TODO move this to BytesReadTracker
+ session.progress(writer.getFilename(), ProgressInfo.Direction.IN, in.getBytesRead(), totalSize);
+ }
+ logger.debug("[Stream #{}] Finished receiving file #{} from {} readBytes = {}, totalSize = {}",
+ session.planId(), fileSeqNum, session.peer, FBUtilities.prettyPrintMemory(in.getBytesRead()), FBUtilities.prettyPrintMemory(totalSize));
+ return writer;
+ }
+ catch (Throwable e)
+ {
+ Object partitionKey = deserializer != null ? deserializer.partitionKey() : "";
+ logger.warn("[Stream {}] Error while reading partition {} from stream on ks='{}' and table='{}'.",
+ session.planId(), partitionKey, cfs.keyspace.getName(), cfs.getTableName(), e);
+ if (writer != null)
+ {
+ writer.abort(e);
+ }
+ throw Throwables.propagate(e);
+ }
+ }
+
+ protected SerializationHeader getHeader(TableMetadata metadata)
+ {
+ return header != null? header.toHeader(metadata) : null; //pre-3.0 sstable have no SerializationHeader
+ }
+
+ protected SSTableMultiWriter createWriter(ColumnFamilyStore cfs, long totalSize, long repairedAt, UUID pendingRepair, SSTableFormat.Type format) throws IOException
+ {
+ Directories.DataDirectory localDir = cfs.getDirectories().getWriteableLocation(totalSize);
+ if (localDir == null)
+ throw new IOException(String.format("Insufficient disk space to store %s", FBUtilities.prettyPrintMemory(totalSize)));
+
+ StreamReceiver streamReceiver = session.getAggregator(tableId);
+ Preconditions.checkState(streamReceiver instanceof CassandraStreamReceiver);
+ LifecycleTransaction txn = CassandraStreamReceiver.fromReceiver(session.getAggregator(tableId)).getTransaction();
+
+ RangeAwareSSTableWriter writer = new RangeAwareSSTableWriter(cfs, estimatedKeys, repairedAt, pendingRepair, format, sstableLevel, totalSize, txn, getHeader(cfs.metadata()));
+ return writer;
+ }
+
+ protected long totalSize()
+ {
+ long size = 0;
+ for (Pair<Long, Long> section : sections)
+ size += section.right - section.left;
+ return size;
+ }
+
+ protected void writePartition(StreamDeserializer deserializer, SSTableMultiWriter writer) throws IOException
+ {
+ writer.append(deserializer.newPartition());
+ deserializer.checkForExceptions();
+ }
+
+ public static class StreamDeserializer extends UnmodifiableIterator<Unfiltered> implements UnfilteredRowIterator
+ {
+ private final TableMetadata metadata;
+ private final DataInputPlus in;
+ private final SerializationHeader header;
+ private final SerializationHelper helper;
+
+ private DecoratedKey key;
+ private DeletionTime partitionLevelDeletion;
+ private SSTableSimpleIterator iterator;
+ private Row staticRow;
+ private IOException exception;
+
+ public StreamDeserializer(TableMetadata metadata, DataInputPlus in, Version version, SerializationHeader header) throws IOException
+ {
+ this.metadata = metadata;
+ this.in = in;
+ this.helper = new SerializationHelper(metadata, version.correspondingMessagingVersion(), SerializationHelper.Flag.PRESERVE_SIZE);
+ this.header = header;
+ }
+
+ public StreamDeserializer newPartition() throws IOException
+ {
+ key = metadata.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(in));
+ partitionLevelDeletion = DeletionTime.serializer.deserialize(in);
+ iterator = SSTableSimpleIterator.create(metadata, in, header, helper, partitionLevelDeletion);
+ staticRow = iterator.readStaticRow();
+ return this;
+ }
+
+ public TableMetadata metadata()
+ {
+ return metadata;
+ }
+
+ public RegularAndStaticColumns columns()
+ {
+ // We don't know which columns we'll get so assume it can be all of them
+ return metadata.regularAndStaticColumns();
+ }
+
+ public boolean isReverseOrder()
+ {
+ return false;
+ }
+
+ public DecoratedKey partitionKey()
+ {
+ return key;
+ }
+
+ public DeletionTime partitionLevelDeletion()
+ {
+ return partitionLevelDeletion;
+ }
+
+ public Row staticRow()
+ {
+ return staticRow;
+ }
+
+ public EncodingStats stats()
+ {
+ return header.stats();
+ }
+
+ public boolean hasNext()
+ {
+ try
+ {
+ return iterator.hasNext();
+ }
+ catch (IOError e)
+ {
+ if (e.getCause() != null && e.getCause() instanceof IOException)
+ {
+ exception = (IOException)e.getCause();
+ return false;
+ }
+ throw e;
+ }
+ }
+
+ public Unfiltered next()
+ {
+ // Note that in practice we know that IOException will be thrown by hasNext(), because that's
+ // where the actual reading happens, so we don't bother catching RuntimeException here (contrarily
+ // to what we do in hasNext)
+ Unfiltered unfiltered = iterator.next();
+ return metadata.isCounter() && unfiltered.kind() == Unfiltered.Kind.ROW
+ ? maybeMarkLocalToBeCleared((Row) unfiltered)
+ : unfiltered;
+ }
+
+ private Row maybeMarkLocalToBeCleared(Row row)
+ {
+ return metadata.isCounter() ? row.markCounterLocalToBeCleared() : row;
+ }
+
+ public void checkForExceptions() throws IOException
+ {
+ if (exception != null)
+ throw exception;
+ }
+
+ public void close()
+ {
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CassandraStreamReceiver.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CassandraStreamReceiver.java b/src/java/org/apache/cassandra/db/streaming/CassandraStreamReceiver.java
new file mode 100644
index 0000000..6a57e49
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CassandraStreamReceiver.java
@@ -0,0 +1,248 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db.streaming;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.Mutation;
+import org.apache.cassandra.db.compaction.OperationType;
+import org.apache.cassandra.db.filter.ColumnFilter;
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.db.partitions.PartitionUpdate;
+import org.apache.cassandra.db.rows.ThrottledUnfilteredIterator;
+import org.apache.cassandra.db.rows.UnfilteredRowIterator;
+import org.apache.cassandra.db.view.View;
+import org.apache.cassandra.dht.Bounds;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.io.sstable.ISSTableScanner;
+import org.apache.cassandra.io.sstable.SSTableMultiWriter;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.streaming.IncomingStream;
+import org.apache.cassandra.streaming.StreamReceiver;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.utils.CloseableIterator;
+import org.apache.cassandra.utils.Throwables;
+import org.apache.cassandra.utils.concurrent.Refs;
+
+public class CassandraStreamReceiver implements StreamReceiver
+{
+ private static final Logger logger = LoggerFactory.getLogger(CassandraStreamReceiver.class);
+
+ private static final int MAX_ROWS_PER_BATCH = Integer.getInteger("cassandra.repair.mutation_repair_rows_per_batch", 100);
+
+ private final ColumnFamilyStore cfs;
+ private final StreamSession session;
+
+ // Transaction tracking new files received
+ private final LifecycleTransaction txn;
+
+ // holds references to SSTables received
+ protected Collection<SSTableReader> sstables;
+
+ private final boolean requiresWritePath;
+
+
+ public CassandraStreamReceiver(ColumnFamilyStore cfs, StreamSession session, int totalFiles)
+ {
+ this.cfs = cfs;
+ this.session = session;
+ // this is an "offline" transaction, as we currently manually expose the sstables once done;
+ // this should be revisited at a later date, so that LifecycleTransaction manages all sstable state changes
+ this.txn = LifecycleTransaction.offline(OperationType.STREAM);
+ this.sstables = new ArrayList<>(totalFiles);
+ this.requiresWritePath = requiresWritePath(cfs);
+ }
+
+ public LifecycleTransaction getTransaction()
+ {
+ return txn;
+ }
+
+ public static CassandraStreamReceiver fromReceiver(StreamReceiver receiver)
+ {
+ Preconditions.checkArgument(receiver instanceof CassandraStreamReceiver);
+ return (CassandraStreamReceiver) receiver;
+ }
+
+ private static CassandraIncomingFile getFile(IncomingStream stream)
+ {
+ Preconditions.checkArgument(stream instanceof CassandraIncomingFile, "Wrong stream type: {}", stream);
+ return (CassandraIncomingFile) stream;
+ }
+
+ @Override
+ public void received(IncomingStream stream)
+ {
+ CassandraIncomingFile file = getFile(stream);
+
+ Collection<SSTableReader> finished = null;
+ SSTableMultiWriter sstable = file.getSSTable();
+ try
+ {
+ finished = sstable.finish(true);
+ }
+ catch (Throwable t)
+ {
+ Throwables.maybeFail(sstable.abort(t));
+ }
+ txn.update(finished, false);
+ sstables.addAll(finished);
+ }
+
+ @Override
+ public void discardStream(IncomingStream stream)
+ {
+ CassandraIncomingFile file = getFile(stream);
+ Throwables.maybeFail(file.getSSTable().abort(null));
+ }
+
+ @Override
+ public void abort()
+ {
+ sstables.clear();
+ txn.abort();
+ }
+
+ private boolean hasViews(ColumnFamilyStore cfs)
+ {
+ return !Iterables.isEmpty(View.findAll(cfs.metadata.keyspace, cfs.getTableName()));
+ }
+
+ private boolean hasCDC(ColumnFamilyStore cfs)
+ {
+ return cfs.metadata().params.cdc;
+ }
+
+ /*
+ * We have a special path for views and for CDC.
+ *
+ * For views, since the view requires cleaning up any pre-existing state, we must put all partitions
+ * through the same write path as normal mutations. This also ensures any 2is are also updated.
+ *
+ * For CDC-enabled tables, we want to ensure that the mutations are run through the CommitLog so they
+ * can be archived by the CDC process on discard.
+ */
+ private boolean requiresWritePath(ColumnFamilyStore cfs) {
+ return hasCDC(cfs) || (session.streamOperation().requiresViewBuild() && hasViews(cfs));
+ }
+
+ private void sendThroughWritePath(ColumnFamilyStore cfs, Collection<SSTableReader> readers) {
+ boolean hasCdc = hasCDC(cfs);
+ ColumnFilter filter = ColumnFilter.all(cfs.metadata());
+ for (SSTableReader reader : readers)
+ {
+ Keyspace ks = Keyspace.open(reader.getKeyspaceName());
+ // When doing mutation-based repair we split each partition into smaller batches
+ // ({@link Stream MAX_ROWS_PER_BATCH}) to avoid OOMing and generating heap pressure
+ try (ISSTableScanner scanner = reader.getScanner();
+ CloseableIterator<UnfilteredRowIterator> throttledPartitions = ThrottledUnfilteredIterator.throttle(scanner, MAX_ROWS_PER_BATCH))
+ {
+ while (throttledPartitions.hasNext())
+ {
+ // MV *can* be applied unsafe if there's no CDC on the CFS as we flush
+ // before transaction is done.
+ //
+ // If the CFS has CDC, however, these updates need to be written to the CommitLog
+ // so they get archived into the cdc_raw folder
+ ks.apply(new Mutation(PartitionUpdate.fromIterator(throttledPartitions.next(), filter)),
+ hasCdc,
+ true,
+ false);
+ }
+ }
+ }
+ }
+
+ private synchronized void finishTransaction()
+ {
+ txn.finish();
+ }
+
+ @Override
+ public void finished()
+ {
+ boolean requiresWritePath = requiresWritePath(cfs);
+ Collection<SSTableReader> readers = sstables;
+
+ try (Refs<SSTableReader> refs = Refs.ref(readers))
+ {
+ if (requiresWritePath)
+ {
+ sendThroughWritePath(cfs, readers);
+ }
+ else
+ {
+ finishTransaction();
+
+ // add sstables (this will build secondary indexes too, see CASSANDRA-10130)
+ logger.debug("[Stream #{}] Received {} sstables from {} ({})", session.planId(), readers.size(), session.peer, readers);
+ cfs.addSSTables(readers);
+
+ //invalidate row and counter cache
+ if (cfs.isRowCacheEnabled() || cfs.metadata().isCounter())
+ {
+ List<Bounds<Token>> boundsToInvalidate = new ArrayList<>(readers.size());
+ readers.forEach(sstable -> boundsToInvalidate.add(new Bounds<Token>(sstable.first.getToken(), sstable.last.getToken())));
+ Set<Bounds<Token>> nonOverlappingBounds = Bounds.getNonOverlappingBounds(boundsToInvalidate);
+
+ if (cfs.isRowCacheEnabled())
+ {
+ int invalidatedKeys = cfs.invalidateRowCache(nonOverlappingBounds);
+ if (invalidatedKeys > 0)
+ logger.debug("[Stream #{}] Invalidated {} row cache entries on table {}.{} after stream " +
+ "receive task completed.", session.planId(), invalidatedKeys,
+ cfs.keyspace.getName(), cfs.getTableName());
+ }
+
+ if (cfs.metadata().isCounter())
+ {
+ int invalidatedKeys = cfs.invalidateCounterCache(nonOverlappingBounds);
+ if (invalidatedKeys > 0)
+ logger.debug("[Stream #{}] Invalidated {} counter cache entries on table {}.{} after stream " +
+ "receive task completed.", session.planId(), invalidatedKeys,
+ cfs.keyspace.getName(), cfs.getTableName());
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public void cleanup()
+ {
+ // We don't keep the streamed sstables since we've applied them manually so we abort the txn and delete
+ // the streamed sstables.
+ if (requiresWritePath)
+ {
+ cfs.forceBlockingFlush();
+ abort();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CassandraStreamWriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CassandraStreamWriter.java b/src/java/org/apache/cassandra/db/streaming/CassandraStreamWriter.java
new file mode 100644
index 0000000..b86f99a
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CassandraStreamWriter.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.streaming;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Collection;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.io.sstable.Component;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.io.util.ChannelProxy;
+import org.apache.cassandra.io.util.DataIntegrityMetadata;
+import org.apache.cassandra.io.util.DataIntegrityMetadata.ChecksumValidator;
+import org.apache.cassandra.io.util.DataOutputStreamPlus;
+import org.apache.cassandra.io.util.FileUtils;
+import org.apache.cassandra.streaming.ProgressInfo;
+import org.apache.cassandra.streaming.StreamManager;
+import org.apache.cassandra.streaming.StreamManager.StreamRateLimiter;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.streaming.compress.ByteBufCompressionDataOutputStreamPlus;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.Pair;
+
+/**
+ * CassandraStreamWriter writes given section of the SSTable to given channel.
+ */
+public class CassandraStreamWriter
+{
+ private static final int DEFAULT_CHUNK_SIZE = 64 * 1024;
+
+ private static final Logger logger = LoggerFactory.getLogger(CassandraStreamWriter.class);
+
+ protected final SSTableReader sstable;
+ protected final Collection<Pair<Long, Long>> sections;
+ protected final StreamRateLimiter limiter;
+ protected final StreamSession session;
+
+ public CassandraStreamWriter(SSTableReader sstable, Collection<Pair<Long, Long>> sections, StreamSession session)
+ {
+ this.session = session;
+ this.sstable = sstable;
+ this.sections = sections;
+ this.limiter = StreamManager.getRateLimiter(session.peer);
+ }
+
+ /**
+ * Stream file of specified sections to given channel.
+ *
+ * CassandraStreamWriter uses LZF compression on wire to decrease size to transfer.
+ *
+ * @param output where this writes data to
+ * @throws IOException on any I/O error
+ */
+ public void write(DataOutputStreamPlus output) throws IOException
+ {
+ long totalSize = totalSize();
+ logger.debug("[Stream #{}] Start streaming file {} to {}, repairedAt = {}, totalSize = {}", session.planId(),
+ sstable.getFilename(), session.peer, sstable.getSSTableMetadata().repairedAt, totalSize);
+
+ try(ChannelProxy proxy = sstable.getDataChannel().sharedCopy();
+ ChecksumValidator validator = new File(sstable.descriptor.filenameFor(Component.CRC)).exists()
+ ? DataIntegrityMetadata.checksumValidator(sstable.descriptor)
+ : null)
+ {
+ int bufferSize = validator == null ? DEFAULT_CHUNK_SIZE: validator.chunkSize;
+
+ // setting up data compression stream
+ long progress = 0L;
+
+ try (DataOutputStreamPlus compressedOutput = new ByteBufCompressionDataOutputStreamPlus(output, limiter))
+ {
+ // stream each of the required sections of the file
+ for (Pair<Long, Long> section : sections)
+ {
+ long start = validator == null ? section.left : validator.chunkStart(section.left);
+ // if the transfer does not start on the valididator's chunk boundary, this is the number of bytes to offset by
+ int transferOffset = (int) (section.left - start);
+ if (validator != null)
+ validator.seek(start);
+
+ // length of the section to read
+ long length = section.right - start;
+ // tracks write progress
+ long bytesRead = 0;
+ while (bytesRead < length)
+ {
+ int toTransfer = (int) Math.min(bufferSize, length - bytesRead);
+ long lastBytesRead = write(proxy, validator, compressedOutput, start, transferOffset, toTransfer, bufferSize);
+ start += lastBytesRead;
+ bytesRead += lastBytesRead;
+ progress += (lastBytesRead - transferOffset);
+ session.progress(sstable.descriptor.filenameFor(Component.DATA), ProgressInfo.Direction.OUT, progress, totalSize);
+ transferOffset = 0;
+ }
+
+ // make sure that current section is sent
+ output.flush();
+ }
+ logger.debug("[Stream #{}] Finished streaming file {} to {}, bytesTransferred = {}, totalSize = {}",
+ session.planId(), sstable.getFilename(), session.peer, FBUtilities.prettyPrintMemory(progress), FBUtilities.prettyPrintMemory(totalSize));
+ }
+ }
+ }
+
+ protected long totalSize()
+ {
+ long size = 0;
+ for (Pair<Long, Long> section : sections)
+ size += section.right - section.left;
+ return size;
+ }
+
+ /**
+ * Sequentially read bytes from the file and write them to the output stream
+ *
+ * @param proxy The file reader to read from
+ * @param validator validator to verify data integrity
+ * @param start The readd offset from the beginning of the {@code proxy} file.
+ * @param transferOffset number of bytes to skip transfer, but include for validation.
+ * @param toTransfer The number of bytes to be transferred.
+ *
+ * @return Number of bytes transferred.
+ *
+ * @throws java.io.IOException on any I/O error
+ */
+ protected long write(ChannelProxy proxy, ChecksumValidator validator, DataOutputStreamPlus output, long start, int transferOffset, int toTransfer, int bufferSize) throws IOException
+ {
+ // the count of bytes to read off disk
+ int minReadable = (int) Math.min(bufferSize, proxy.size() - start);
+
+ // this buffer will hold the data from disk. as it will be compressed on the fly by
+ // ByteBufCompressionDataOutputStreamPlus.write(ByteBuffer), we can release this buffer as soon as we can.
+ ByteBuffer buffer = ByteBuffer.allocateDirect(minReadable);
+ try
+ {
+ int readCount = proxy.read(buffer, start);
+ assert readCount == minReadable : String.format("could not read required number of bytes from file to be streamed: read %d bytes, wanted %d bytes", readCount, minReadable);
+ buffer.flip();
+
+ if (validator != null)
+ {
+ validator.validate(buffer);
+ buffer.flip();
+ }
+
+ buffer.position(transferOffset);
+ buffer.limit(transferOffset + (toTransfer - transferOffset));
+ output.write(buffer);
+ }
+ finally
+ {
+ FileUtils.clean(buffer);
+ }
+
+ return toTransfer;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamReader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamReader.java b/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamReader.java
new file mode 100644
index 0000000..343d7ed
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamReader.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.streaming;
+
+import java.io.IOException;
+
+import com.google.common.base.Throwables;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.io.compress.CompressionMetadata;
+import org.apache.cassandra.io.sstable.SSTableMultiWriter;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.TrackedDataInputPlus;
+import org.apache.cassandra.streaming.ProgressInfo;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.streaming.messages.StreamMessageHeader;
+import org.apache.cassandra.utils.ChecksumType;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.Pair;
+
+import static org.apache.cassandra.utils.Throwables.extractIOExceptionCause;
+
+/**
+ * CassandraStreamReader that reads from streamed compressed SSTable
+ */
+public class CompressedCassandraStreamReader extends CassandraStreamReader
+{
+ private static final Logger logger = LoggerFactory.getLogger(CompressedCassandraStreamReader.class);
+
+ protected final CompressionInfo compressionInfo;
+
+ public CompressedCassandraStreamReader(StreamMessageHeader header, CassandraStreamHeader streamHeader, StreamSession session)
+ {
+ super(header, streamHeader, session);
+ this.compressionInfo = streamHeader.compressionInfo;
+ }
+
+ /**
+ * @return SSTable transferred
+ * @throws java.io.IOException if reading the remote sstable fails. Will throw an RTE if local write fails.
+ */
+ @Override
+ @SuppressWarnings("resource") // input needs to remain open, streams on top of it can't be closed
+ public SSTableMultiWriter read(DataInputPlus inputPlus) throws IOException
+ {
+ long totalSize = totalSize();
+
+ ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(tableId);
+
+ if (cfs == null)
+ {
+ // schema was dropped during streaming
+ throw new IOException("CF " + tableId + " was dropped during streaming");
+ }
+
+ logger.debug("[Stream #{}] Start receiving file #{} from {}, repairedAt = {}, size = {}, ks = '{}', pendingRepair = '{}', table = '{}'.",
+ session.planId(), fileSeqNum, session.peer, repairedAt, totalSize, cfs.keyspace.getName(), pendingRepair,
+ cfs.getTableName());
+
+ StreamDeserializer deserializer = null;
+ SSTableMultiWriter writer = null;
+ try (CompressedInputStream cis = new CompressedInputStream(inputPlus, compressionInfo, ChecksumType.CRC32, cfs::getCrcCheckChance))
+ {
+ TrackedDataInputPlus in = new TrackedDataInputPlus(cis);
+ deserializer = new StreamDeserializer(cfs.metadata(), in, inputVersion, getHeader(cfs.metadata()));
+ writer = createWriter(cfs, totalSize, repairedAt, pendingRepair, format);
+ String filename = writer.getFilename();
+ int sectionIdx = 0;
+ for (Pair<Long, Long> section : sections)
+ {
+ assert cis.getTotalCompressedBytesRead() <= totalSize;
+ long sectionLength = section.right - section.left;
+
+ logger.trace("[Stream #{}] Reading section {} with length {} from stream.", session.planId(), sectionIdx++, sectionLength);
+ // skip to beginning of section inside chunk
+ cis.position(section.left);
+ in.reset(0);
+
+ while (in.getBytesRead() < sectionLength)
+ {
+ writePartition(deserializer, writer);
+ // when compressed, report total bytes of compressed chunks read since remoteFile.size is the sum of chunks transferred
+ session.progress(filename, ProgressInfo.Direction.IN, cis.getTotalCompressedBytesRead(), totalSize);
+ }
+ }
+ logger.debug("[Stream #{}] Finished receiving file #{} from {} readBytes = {}, totalSize = {}", session.planId(), fileSeqNum,
+ session.peer, FBUtilities.prettyPrintMemory(cis.getTotalCompressedBytesRead()), FBUtilities.prettyPrintMemory(totalSize));
+ return writer;
+ }
+ catch (Throwable e)
+ {
+ Object partitionKey = deserializer != null ? deserializer.partitionKey() : "";
+ logger.warn("[Stream {}] Error while reading partition {} from stream on ks='{}' and table='{}'.",
+ session.planId(), partitionKey, cfs.keyspace.getName(), cfs.getTableName());
+ if (writer != null)
+ {
+ writer.abort(e);
+ }
+ if (extractIOExceptionCause(e).isPresent())
+ throw e;
+ throw Throwables.propagate(e);
+ }
+ }
+
+ @Override
+ protected long totalSize()
+ {
+ long size = 0;
+ // calculate total length of transferring chunks
+ for (CompressionMetadata.Chunk chunk : compressionInfo.chunks)
+ size += chunk.length + 4; // 4 bytes for CRC
+ return size;
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamWriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamWriter.java b/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamWriter.java
new file mode 100644
index 0000000..3fcbc38
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CompressedCassandraStreamWriter.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.streaming;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.io.compress.CompressionMetadata;
+import org.apache.cassandra.io.sstable.Component;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.io.util.ChannelProxy;
+import org.apache.cassandra.io.util.DataOutputStreamPlus;
+import org.apache.cassandra.io.util.FileUtils;
+import org.apache.cassandra.net.async.ByteBufDataOutputStreamPlus;
+import org.apache.cassandra.streaming.ProgressInfo;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.Pair;
+
+/**
+ * CassandraStreamWriter for compressed SSTable.
+ */
+public class CompressedCassandraStreamWriter extends CassandraStreamWriter
+{
+ private static final int CHUNK_SIZE = 1 << 16;
+
+ private static final Logger logger = LoggerFactory.getLogger(CompressedCassandraStreamWriter.class);
+
+ private final CompressionInfo compressionInfo;
+
+ public CompressedCassandraStreamWriter(SSTableReader sstable, Collection<Pair<Long, Long>> sections, CompressionInfo compressionInfo, StreamSession session)
+ {
+ super(sstable, sections, session);
+ this.compressionInfo = compressionInfo;
+ }
+
+ @Override
+ public void write(DataOutputStreamPlus out) throws IOException
+ {
+ assert out instanceof ByteBufDataOutputStreamPlus;
+ ByteBufDataOutputStreamPlus output = (ByteBufDataOutputStreamPlus)out;
+ long totalSize = totalSize();
+ logger.debug("[Stream #{}] Start streaming file {} to {}, repairedAt = {}, totalSize = {}", session.planId(),
+ sstable.getFilename(), session.peer, sstable.getSSTableMetadata().repairedAt, totalSize);
+ try (ChannelProxy fc = sstable.getDataChannel().sharedCopy())
+ {
+ long progress = 0L;
+ // calculate chunks to transfer. we want to send continuous chunks altogether.
+ List<Pair<Long, Long>> sections = getTransferSections(compressionInfo.chunks);
+
+ int sectionIdx = 0;
+
+ // stream each of the required sections of the file
+ for (final Pair<Long, Long> section : sections)
+ {
+ // length of the section to stream
+ long length = section.right - section.left;
+
+ logger.trace("[Stream #{}] Writing section {} with length {} to stream.", session.planId(), sectionIdx++, length);
+
+ // tracks write progress
+ long bytesTransferred = 0;
+ while (bytesTransferred < length)
+ {
+ final int toTransfer = (int) Math.min(CHUNK_SIZE, length - bytesTransferred);
+ limiter.acquire(toTransfer);
+
+ ByteBuffer outBuffer = ByteBuffer.allocateDirect(toTransfer);
+ long lastWrite;
+ try
+ {
+ lastWrite = fc.read(outBuffer, section.left + bytesTransferred);
+ assert lastWrite == toTransfer : String.format("could not read required number of bytes from file to be streamed: read %d bytes, wanted %d bytes", lastWrite, toTransfer);
+ outBuffer.flip();
+ output.writeToChannel(outBuffer);
+ }
+ catch (IOException e)
+ {
+ FileUtils.clean(outBuffer);
+ throw e;
+ }
+
+ bytesTransferred += lastWrite;
+ progress += lastWrite;
+ session.progress(sstable.descriptor.filenameFor(Component.DATA), ProgressInfo.Direction.OUT, progress, totalSize);
+ }
+ }
+ logger.debug("[Stream #{}] Finished streaming file {} to {}, bytesTransferred = {}, totalSize = {}",
+ session.planId(), sstable.getFilename(), session.peer, FBUtilities.prettyPrintMemory(progress), FBUtilities.prettyPrintMemory(totalSize));
+ }
+ }
+
+ @Override
+ protected long totalSize()
+ {
+ long size = 0;
+ // calculate total length of transferring chunks
+ for (CompressionMetadata.Chunk chunk : compressionInfo.chunks)
+ size += chunk.length + 4; // 4 bytes for CRC
+ return size;
+ }
+
+ // chunks are assumed to be sorted by offset
+ private List<Pair<Long, Long>> getTransferSections(CompressionMetadata.Chunk[] chunks)
+ {
+ List<Pair<Long, Long>> transferSections = new ArrayList<>();
+ Pair<Long, Long> lastSection = null;
+ for (CompressionMetadata.Chunk chunk : chunks)
+ {
+ if (lastSection != null)
+ {
+ if (chunk.offset == lastSection.right)
+ {
+ // extend previous section to end of this chunk
+ lastSection = Pair.create(lastSection.left, chunk.offset + chunk.length + 4); // 4 bytes for CRC
+ }
+ else
+ {
+ transferSections.add(lastSection);
+ lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4);
+ }
+ }
+ else
+ {
+ lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4);
+ }
+ }
+ if (lastSection != null)
+ transferSections.add(lastSection);
+ return transferSections;
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
[4/5] cassandra git commit: Abstract streaming for pluggable storage
Posted by bd...@apache.org.
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CompressedInputStream.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CompressedInputStream.java b/src/java/org/apache/cassandra/db/streaming/CompressedInputStream.java
new file mode 100644
index 0000000..2f56786
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CompressedInputStream.java
@@ -0,0 +1,285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.streaming;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ReadableByteChannel;
+import java.util.Iterator;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.DoubleSupplier;
+
+import com.google.common.collect.Iterators;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.netty.util.concurrent.FastThreadLocalThread;
+import org.apache.cassandra.io.compress.CompressionMetadata;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.FileUtils;
+import org.apache.cassandra.io.util.RebufferingInputStream;
+import org.apache.cassandra.db.streaming.CassandraStreamReader.StreamDeserializer;
+import org.apache.cassandra.utils.ChecksumType;
+import org.apache.cassandra.utils.WrappedRunnable;
+
+/**
+ * InputStream which reads data from underlining source with given {@link CompressionInfo}. Uses {@link #buffer} as a buffer
+ * for uncompressed data (which is read by stream consumers - {@link StreamDeserializer} in this case).
+ */
+public class CompressedInputStream extends RebufferingInputStream implements AutoCloseable
+{
+
+ private static final Logger logger = LoggerFactory.getLogger(CompressedInputStream.class);
+
+ private final CompressionInfo info;
+ // chunk buffer
+ private final BlockingQueue<ByteBuffer> dataBuffer;
+ private final DoubleSupplier crcCheckChanceSupplier;
+
+ /**
+ * The base offset of the current {@link #buffer} from the beginning of the stream.
+ */
+ private long bufferOffset = 0;
+
+ /**
+ * The current {@link CompressedCassandraStreamReader#sections} offset in the stream.
+ */
+ private long current = 0;
+
+ private final ChecksumType checksumType;
+
+ private static final int CHECKSUM_LENGTH = 4;
+
+ /**
+ * Indicates there was a problem when reading from source stream.
+ * When this is added to the <code>dataBuffer</code> by the stream Reader,
+ * it is expected that the <code>readException</code> variable is populated
+ * with the cause of the error when reading from source stream, so it is
+ * thrown to the consumer on subsequent read operation.
+ */
+ private static final ByteBuffer POISON_PILL = ByteBuffer.wrap(new byte[0]);
+
+ private volatile IOException readException = null;
+
+ private long totalCompressedBytesRead;
+
+ /**
+ * @param source Input source to read compressed data from
+ * @param info Compression info
+ */
+ public CompressedInputStream(DataInputPlus source, CompressionInfo info, ChecksumType checksumType, DoubleSupplier crcCheckChanceSupplier)
+ {
+ super(ByteBuffer.allocateDirect(info.parameters.chunkLength()));
+ buffer.limit(buffer.position()); // force the buffer to appear "consumed" so that it triggers reBuffer on the first read
+ this.info = info;
+ this.dataBuffer = new ArrayBlockingQueue<>(Math.min(info.chunks.length, 1024));
+ this.crcCheckChanceSupplier = crcCheckChanceSupplier;
+ this.checksumType = checksumType;
+
+ new FastThreadLocalThread(new Reader(source, info, dataBuffer)).start();
+ }
+
+ /**
+ * Invoked when crossing into the next stream boundary in {@link CompressedCassandraStreamReader#sections}.
+ */
+ public void position(long position) throws IOException
+ {
+ if (readException != null)
+ throw readException;
+
+ assert position >= current : "stream can only read forward.";
+ current = position;
+
+ if (current > bufferOffset + buffer.limit())
+ reBuffer(false);
+
+ buffer.position((int)(current - bufferOffset));
+ }
+
+ protected void reBuffer() throws IOException
+ {
+ reBuffer(true);
+ }
+
+ private void reBuffer(boolean updateCurrent) throws IOException
+ {
+ if (readException != null)
+ {
+ FileUtils.clean(buffer);
+ buffer = null;
+ throw readException;
+ }
+
+ // increment the offset into the stream based on the current buffer's read count
+ if (updateCurrent)
+ current += buffer.position();
+
+ try
+ {
+ ByteBuffer compressedWithCRC = dataBuffer.take();
+ if (compressedWithCRC == POISON_PILL)
+ {
+ assert readException != null;
+ throw readException;
+ }
+
+ decompress(compressedWithCRC);
+ }
+ catch (InterruptedException e)
+ {
+ throw new EOFException("No chunk available");
+ }
+ }
+
+ private void decompress(ByteBuffer compressed) throws IOException
+ {
+ int length = compressed.remaining();
+
+ // uncompress if the buffer size is less than the max chunk size. else, if the buffer size is greater than or equal to the maxCompressedLength,
+ // we assume the buffer is not compressed. see CASSANDRA-10520
+ final boolean releaseCompressedBuffer;
+ if (length - CHECKSUM_LENGTH < info.parameters.maxCompressedLength())
+ {
+ buffer.clear();
+ compressed.limit(length - CHECKSUM_LENGTH);
+ info.parameters.getSstableCompressor().uncompress(compressed, buffer);
+ buffer.flip();
+ releaseCompressedBuffer = true;
+ }
+ else
+ {
+ FileUtils.clean(buffer);
+ buffer = compressed;
+ buffer.limit(length - CHECKSUM_LENGTH);
+ releaseCompressedBuffer = false;
+ }
+ totalCompressedBytesRead += length;
+
+ // validate crc randomly
+ double crcCheckChance = this.crcCheckChanceSupplier.getAsDouble();
+ if (crcCheckChance >= 1d ||
+ (crcCheckChance > 0d && crcCheckChance > ThreadLocalRandom.current().nextDouble()))
+ {
+ ByteBuffer crcBuf = compressed.duplicate();
+ crcBuf.limit(length - CHECKSUM_LENGTH).position(0);
+ int checksum = (int) checksumType.of(crcBuf);
+
+ crcBuf.limit(length);
+ if (crcBuf.getInt() != checksum)
+ throw new IOException("CRC unmatched");
+ }
+
+ if (releaseCompressedBuffer)
+ FileUtils.clean(compressed);
+
+ // buffer offset is always aligned
+ final int compressedChunkLength = info.parameters.chunkLength();
+ bufferOffset = current & ~(compressedChunkLength - 1);
+ }
+
+ public long getTotalCompressedBytesRead()
+ {
+ return totalCompressedBytesRead;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Releases the resources specific to this instance, but not the {@link DataInputPlus} that is used by the {@link Reader}.
+ */
+ @Override
+ public void close()
+ {
+ if (buffer != null)
+ {
+ FileUtils.clean(buffer);
+ buffer = null;
+ }
+ }
+
+ class Reader extends WrappedRunnable
+ {
+ private final DataInputPlus source;
+ private final Iterator<CompressionMetadata.Chunk> chunks;
+ private final BlockingQueue<ByteBuffer> dataBuffer;
+
+ Reader(DataInputPlus source, CompressionInfo info, BlockingQueue<ByteBuffer> dataBuffer)
+ {
+ this.source = source;
+ this.chunks = Iterators.forArray(info.chunks);
+ this.dataBuffer = dataBuffer;
+ }
+
+ protected void runMayThrow() throws Exception
+ {
+ byte[] tmp = null;
+ while (chunks.hasNext())
+ {
+ CompressionMetadata.Chunk chunk = chunks.next();
+
+ int readLength = chunk.length + 4; // read with CRC
+ ByteBuffer compressedWithCRC = null;
+ try
+ {
+ final int r;
+ if (source instanceof ReadableByteChannel)
+ {
+ compressedWithCRC = ByteBuffer.allocateDirect(readLength);
+ r = ((ReadableByteChannel)source).read(compressedWithCRC);
+ compressedWithCRC.flip();
+ }
+ else
+ {
+ // read into an on-heap araay, then copy over to an off-heap buffer. at a minumum snappy requires
+ // off-heap buffers for decompression, else we could have just wrapped the plain byte array in a ByteBuffer
+ if (tmp == null || tmp.length < info.parameters.chunkLength() + CHECKSUM_LENGTH)
+ tmp = new byte[info.parameters.chunkLength() + CHECKSUM_LENGTH];
+ source.readFully(tmp, 0, readLength);
+ compressedWithCRC = ByteBuffer.allocateDirect(readLength);
+ compressedWithCRC.put(tmp, 0, readLength);
+ compressedWithCRC.position(0);
+ r = readLength;
+ }
+
+ if (r < 0)
+ {
+ FileUtils.clean(compressedWithCRC);
+ readException = new EOFException("No chunk available");
+ dataBuffer.put(POISON_PILL);
+ return; // throw exception where we consume dataBuffer
+ }
+ }
+ catch (IOException e)
+ {
+ if (!(e instanceof EOFException))
+ logger.warn("Error while reading compressed input stream.", e);
+ if (compressedWithCRC != null)
+ FileUtils.clean(compressedWithCRC);
+
+ readException = e;
+ dataBuffer.put(POISON_PILL);
+ return; // throw exception where we consume dataBuffer
+ }
+ dataBuffer.put(compressedWithCRC);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/CompressionInfo.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/CompressionInfo.java b/src/java/org/apache/cassandra/db/streaming/CompressionInfo.java
new file mode 100644
index 0000000..0f0d5c7
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/CompressionInfo.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.db.streaming;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.cassandra.db.TypeSizes;
+import org.apache.cassandra.io.IVersionedSerializer;
+import org.apache.cassandra.io.compress.CompressionMetadata;
+import org.apache.cassandra.schema.CompressionParams;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.DataOutputPlus;
+import org.apache.cassandra.utils.Pair;
+
+/**
+ * Container that carries compression parameters and chunks to decompress data from stream.
+ */
+public class CompressionInfo
+{
+ public static final IVersionedSerializer<CompressionInfo> serializer = new CompressionInfoSerializer();
+
+ public final CompressionMetadata.Chunk[] chunks;
+ public final CompressionParams parameters;
+
+ public CompressionInfo(CompressionMetadata.Chunk[] chunks, CompressionParams parameters)
+ {
+ assert chunks != null && parameters != null;
+ this.chunks = chunks;
+ this.parameters = parameters;
+ }
+
+ static CompressionInfo fromCompressionMetadata(CompressionMetadata metadata, List<Pair<Long, Long>> sections)
+ {
+ if (metadata == null)
+ {
+ return null;
+ }
+ else
+ {
+ return new CompressionInfo(metadata.getChunksForSections(sections), metadata.parameters);
+ }
+
+ }
+
+ static class CompressionInfoSerializer implements IVersionedSerializer<CompressionInfo>
+ {
+ public void serialize(CompressionInfo info, DataOutputPlus out, int version) throws IOException
+ {
+ if (info == null)
+ {
+ out.writeInt(-1);
+ return;
+ }
+
+ int chunkCount = info.chunks.length;
+ out.writeInt(chunkCount);
+ for (int i = 0; i < chunkCount; i++)
+ CompressionMetadata.Chunk.serializer.serialize(info.chunks[i], out, version);
+ // compression params
+ CompressionParams.serializer.serialize(info.parameters, out, version);
+ }
+
+ public CompressionInfo deserialize(DataInputPlus in, int version) throws IOException
+ {
+ // chunks
+ int chunkCount = in.readInt();
+ if (chunkCount < 0)
+ return null;
+
+ CompressionMetadata.Chunk[] chunks = new CompressionMetadata.Chunk[chunkCount];
+ for (int i = 0; i < chunkCount; i++)
+ chunks[i] = CompressionMetadata.Chunk.serializer.deserialize(in, version);
+
+ // compression params
+ CompressionParams parameters = CompressionParams.serializer.deserialize(in, version);
+ return new CompressionInfo(chunks, parameters);
+ }
+
+ public long serializedSize(CompressionInfo info, int version)
+ {
+ if (info == null)
+ return TypeSizes.sizeof(-1);
+
+ // chunks
+ int chunkCount = info.chunks.length;
+ long size = TypeSizes.sizeof(chunkCount);
+ for (int i = 0; i < chunkCount; i++)
+ size += CompressionMetadata.Chunk.serializer.serializedSize(info.chunks[i], version);
+ // compression params
+ size += CompressionParams.serializer.serializedSize(info.parameters, version);
+ return size;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/db/streaming/package-info.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/db/streaming/package-info.java b/src/java/org/apache/cassandra/db/streaming/package-info.java
new file mode 100644
index 0000000..1e117aa
--- /dev/null
+++ b/src/java/org/apache/cassandra/db/streaming/package-info.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * <h2>File transfer</h2>
+ *
+ * When tranferring whole or subsections of an sstable, only the DATA component is shipped. To that end,
+ * there are three "modes" of an sstable transfer that need to be handled somewhat differently:
+ *
+ * 1) uncompressed sstable - data needs to be read into user space so it can be manipulated: checksum validation,
+ * apply stream compression (see next section), and/or TLS encryption.
+ *
+ * 2) compressed sstable, transferred with SSL/TLS - data needs to be read into user space as that is where the TLS encryption
+ * needs to happen. Netty does not allow the pretense of doing zero-copy transfers when TLS is in the pipeline;
+ * data must explicitly be pulled into user-space memory for TLS encryption to work.
+ *
+ * 3) compressed sstable, transferred without SSL/TLS - data can be streamed via zero-copy transfer as the data does not
+ * need to be manipulated (it can be sent "as-is").
+ *
+ * <h3>Compressing the data</h3>
+ * We always want to transfer as few bytes as possible of the wire when streaming a file. If the
+ * sstable is not already compressed via table compression options, we apply an on-the-fly stream compression
+ * to the data. The stream compression format is documented in
+ * {@link org.apache.cassandra.streaming.async.StreamCompressionSerializer}
+ *
+ * You may be wondering: why implement your own compression scheme? why not use netty's built-in compression codecs,
+ * like {@link io.netty.handler.codec.compression.Lz4FrameEncoder}? That makes complete sense if all the sstables
+ * to be streamed are non using sstable compression (and obviously you wouldn't use stream compression when the sstables
+ * are using sstable compression). The problem is when you have a mix of files, some using sstable compression
+ * and some not. You can either:
+ *
+ * - send the files of one type over one kind of socket, and the others over another socket
+ * - send them both over the same socket, but then auto-adjust per each file type.
+ *
+ * I've opted for the latter to keep socket/channel management simpler and cleaner.
+ *
+ */
+package org.apache.cassandra.db.streaming;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/dht/RangeStreamer.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/dht/RangeStreamer.java b/src/java/org/apache/cassandra/dht/RangeStreamer.java
index 439ebc6..dfabac2 100644
--- a/src/java/org/apache/cassandra/dht/RangeStreamer.java
+++ b/src/java/org/apache/cassandra/dht/RangeStreamer.java
@@ -20,6 +20,7 @@ package org.apache.cassandra.dht;
import java.util.*;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
@@ -155,11 +156,12 @@ public class RangeStreamer
boolean connectSequentially,
int connectionsPerHost)
{
+ Preconditions.checkArgument(streamOperation == StreamOperation.BOOTSTRAP || streamOperation == StreamOperation.REBUILD, streamOperation);
this.metadata = metadata;
this.tokens = tokens;
this.address = address;
this.description = streamOperation.getDescription();
- this.streamPlan = new StreamPlan(streamOperation, connectionsPerHost, true, connectSequentially, null, PreviewKind.NONE);
+ this.streamPlan = new StreamPlan(streamOperation, connectionsPerHost, connectSequentially, null, PreviewKind.NONE);
this.useStrictConsistency = useStrictConsistency;
this.snitch = snitch;
this.stateStore = stateStore;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java b/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
index 7d77ad5..980fdf1 100644
--- a/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
+++ b/src/java/org/apache/cassandra/io/sstable/SSTableLoader.java
@@ -18,12 +18,12 @@
package org.apache.cassandra.io.sstable;
import java.io.File;
-import java.io.IOException;
import java.util.*;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
+import org.apache.cassandra.db.streaming.CassandraOutgoingFile;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.io.FSError;
import org.apache.cassandra.schema.TableMetadataRef;
@@ -52,7 +52,7 @@ public class SSTableLoader implements StreamEventHandler
private final Set<InetAddressAndPort> failedHosts = new HashSet<>();
private final List<SSTableReader> sstables = new ArrayList<>();
- private final Multimap<InetAddressAndPort, StreamSession.SSTableStreamingSections> streamingDetails = HashMultimap.create();
+ private final Multimap<InetAddressAndPort, OutgoingStream> streamingDetails = HashMultimap.create();
public SSTableLoader(File directory, Client client, OutputHandler outputHandler)
{
@@ -131,8 +131,8 @@ public class SSTableLoader implements StreamEventHandler
List<Pair<Long, Long>> sstableSections = sstable.getPositionsForRanges(tokenRanges);
long estimatedKeys = sstable.estimatedKeysForRanges(tokenRanges);
Ref<SSTableReader> ref = sstable.ref();
- StreamSession.SSTableStreamingSections details = new StreamSession.SSTableStreamingSections(ref, sstableSections, estimatedKeys);
- streamingDetails.put(endpoint, details);
+ OutgoingStream stream = new CassandraOutgoingFile(StreamOperation.BULK_LOAD, ref, sstableSections, estimatedKeys);
+ streamingDetails.put(endpoint, stream);
}
// to conserve heap space when bulk loading
@@ -160,7 +160,7 @@ public class SSTableLoader implements StreamEventHandler
client.init(keyspace);
outputHandler.output("Established connection to initial hosts");
- StreamPlan plan = new StreamPlan(StreamOperation.BULK_LOAD, connectionsPerHost, false, false, null, PreviewKind.NONE).connectionFactory(client.getConnectionFactory());
+ StreamPlan plan = new StreamPlan(StreamOperation.BULK_LOAD, connectionsPerHost, false, null, PreviewKind.NONE).connectionFactory(client.getConnectionFactory());
Map<InetAddressAndPort, Collection<Range<Token>>> endpointToRanges = client.getEndpointToRangesMap();
openSSTables(endpointToRanges);
@@ -178,15 +178,15 @@ public class SSTableLoader implements StreamEventHandler
if (toIgnore.contains(remote))
continue;
- List<StreamSession.SSTableStreamingSections> endpointDetails = new LinkedList<>();
+ List<OutgoingStream> streams = new LinkedList<>();
// references are acquired when constructing the SSTableStreamingSections above
- for (StreamSession.SSTableStreamingSections details : streamingDetails.get(remote))
+ for (OutgoingStream stream : streamingDetails.get(remote))
{
- endpointDetails.add(details);
+ streams.add(stream);
}
- plan.transferFiles(remote, endpointDetails);
+ plan.transferStreams(remote, streams);
}
plan.listeners(this, listeners);
return plan.execute();
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/repair/AsymmetricLocalSyncTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/repair/AsymmetricLocalSyncTask.java b/src/java/org/apache/cassandra/repair/AsymmetricLocalSyncTask.java
index 2c4fae4..8d58673 100644
--- a/src/java/org/apache/cassandra/repair/AsymmetricLocalSyncTask.java
+++ b/src/java/org/apache/cassandra/repair/AsymmetricLocalSyncTask.java
@@ -52,7 +52,6 @@ public class AsymmetricLocalSyncTask extends AsymmetricSyncTask implements Strea
InetAddressAndPort preferred = SystemKeyspace.getPreferredIP(fetchFrom);
StreamPlan plan = new StreamPlan(StreamOperation.REPAIR,
1, false,
- false,
pendingRepair,
previewKind)
.listeners(this)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/repair/LocalSyncTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/repair/LocalSyncTask.java b/src/java/org/apache/cassandra/repair/LocalSyncTask.java
index 60d571b..3901c75 100644
--- a/src/java/org/apache/cassandra/repair/LocalSyncTask.java
+++ b/src/java/org/apache/cassandra/repair/LocalSyncTask.java
@@ -61,7 +61,7 @@ public class LocalSyncTask extends SyncTask implements StreamEventHandler
@VisibleForTesting
StreamPlan createStreamPlan(InetAddressAndPort dst, InetAddressAndPort preferred, List<Range<Token>> differences)
{
- StreamPlan plan = new StreamPlan(StreamOperation.REPAIR, 1, false, false, pendingRepair, previewKind)
+ StreamPlan plan = new StreamPlan(StreamOperation.REPAIR, 1, false, pendingRepair, previewKind)
.listeners(this)
.flushBeforeTransfer(pendingRepair == null)
.requestRanges(dst, preferred, desc.keyspace, differences, desc.columnFamily); // request ranges from the remote node
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/repair/StreamingRepairTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/repair/StreamingRepairTask.java b/src/java/org/apache/cassandra/repair/StreamingRepairTask.java
index 0122b31..725e84d 100644
--- a/src/java/org/apache/cassandra/repair/StreamingRepairTask.java
+++ b/src/java/org/apache/cassandra/repair/StreamingRepairTask.java
@@ -79,7 +79,7 @@ public class StreamingRepairTask implements Runnable, StreamEventHandler
@VisibleForTesting
StreamPlan createStreamPlan(InetAddressAndPort dest, InetAddressAndPort preferred)
{
- StreamPlan sp = new StreamPlan(StreamOperation.REPAIR, 1, false, false, pendingRepair, previewKind)
+ StreamPlan sp = new StreamPlan(StreamOperation.REPAIR, 1, false, pendingRepair, previewKind)
.listeners(this)
.flushBeforeTransfer(pendingRepair == null) // sstables are isolated at the beginning of an incremental repair session, so flushing isn't neccessary
.requestRanges(dest, preferred, desc.keyspace, ranges, desc.columnFamily); // request ranges from the remote node
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/IncomingStream.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/IncomingStream.java b/src/java/org/apache/cassandra/streaming/IncomingStream.java
new file mode 100644
index 0000000..18bebf5
--- /dev/null
+++ b/src/java/org/apache/cassandra/streaming/IncomingStream.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.streaming;
+
+import java.io.IOException;
+
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.schema.TableId;
+
+/**
+ * The counterpart of {@link OutgoingStream} on the receiving side.
+ *
+ * Data streamed in can (and should) be persisted, but must not be included in the table's
+ * live data set until added by {@link StreamReceiver}. If the stream fails, the stream receiver will
+ * delete the streamed data, but implementations still need to handle the case where it's process dies
+ * during streaming, and it has data left around on startup, in which case it should be deleted.
+ */
+public interface IncomingStream
+{
+
+ /**
+ * Read in the stream data.
+ */
+ void read(DataInputPlus inputPlus, int version) throws IOException;
+
+ String getName();
+ long getSize();
+ TableId getTableId();
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/OutgoingStream.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/OutgoingStream.java b/src/java/org/apache/cassandra/streaming/OutgoingStream.java
new file mode 100644
index 0000000..e71b985
--- /dev/null
+++ b/src/java/org/apache/cassandra/streaming/OutgoingStream.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.streaming;
+
+import java.io.IOException;
+import java.util.UUID;
+
+import org.apache.cassandra.io.util.DataOutputStreamPlus;
+import org.apache.cassandra.schema.TableId;
+
+/**
+ * Some subset of data to be streamed. Implementations handle writing out their data via the write method.
+ * On the receiving end, {@link IncomingStream} streams the data in.
+ *
+ * All the data contained in a given stream needs to have the same repairedAt timestamp (or 0) and pendingRepair
+ * id (or null).
+ */
+public interface OutgoingStream
+{
+ /**
+ * Write the streams data into the socket
+ */
+ void write(StreamSession session, DataOutputStreamPlus output, int version) throws IOException;
+
+ /**
+ * Release any resources held by the stream
+ */
+ void finish();
+
+ long getRepairedAt();
+ UUID getPendingRepair();
+
+ String getName();
+ long getSize();
+ TableId getTableId();
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/PreviewKind.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/PreviewKind.java b/src/java/org/apache/cassandra/streaming/PreviewKind.java
index 3b4d2a0..51c5746 100644
--- a/src/java/org/apache/cassandra/streaming/PreviewKind.java
+++ b/src/java/org/apache/cassandra/streaming/PreviewKind.java
@@ -21,26 +21,19 @@ package org.apache.cassandra.streaming;
import java.util.UUID;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-
-import org.apache.cassandra.io.sstable.format.SSTableReader;
-
public enum PreviewKind
{
- NONE(0, null),
- ALL(1, Predicates.alwaysTrue()),
- UNREPAIRED(2, Predicates.not(SSTableReader::isRepaired)),
- REPAIRED(3, SSTableReader::isRepaired);
+ NONE(0),
+ ALL(1),
+ UNREPAIRED(2),
+ REPAIRED(3);
private final int serializationVal;
- private final Predicate<SSTableReader> streamingPredicate;
- PreviewKind(int serializationVal, Predicate<SSTableReader> streamingPredicate)
+ PreviewKind(int serializationVal)
{
assert ordinal() == serializationVal;
this.serializationVal = serializationVal;
- this.streamingPredicate = streamingPredicate;
}
public int getSerializationVal()
@@ -53,10 +46,6 @@ public enum PreviewKind
return values()[serializationVal];
}
- public Predicate<SSTableReader> getStreamingPredicate()
- {
- return streamingPredicate;
- }
public boolean isPreview()
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/ProgressInfo.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/ProgressInfo.java b/src/java/org/apache/cassandra/streaming/ProgressInfo.java
index 2334599..ac91855 100644
--- a/src/java/org/apache/cassandra/streaming/ProgressInfo.java
+++ b/src/java/org/apache/cassandra/streaming/ProgressInfo.java
@@ -24,7 +24,7 @@ import com.google.common.base.Objects;
import org.apache.cassandra.locator.InetAddressAndPort;
/**
- * ProgressInfo contains file transfer progress.
+ * ProgressInfo contains stream transfer progress.
*/
public class ProgressInfo implements Serializable
{
@@ -69,7 +69,7 @@ public class ProgressInfo implements Serializable
}
/**
- * @return true if file transfer is completed
+ * @return true if transfer is completed
*/
public boolean isCompleted()
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/SessionInfo.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/SessionInfo.java b/src/java/org/apache/cassandra/streaming/SessionInfo.java
index bbca753..4b4bbed 100644
--- a/src/java/org/apache/cassandra/streaming/SessionInfo.java
+++ b/src/java/org/apache/cassandra/streaming/SessionInfo.java
@@ -70,7 +70,7 @@ public final class SessionInfo implements Serializable
}
/**
- * Update progress of receiving/sending file.
+ * Update progress of receiving/sending stream.
*
* @param newProgress new progress info
*/
@@ -157,11 +157,11 @@ public final class SessionInfo implements Serializable
return getTotalSizes(sendingSummaries);
}
- private long getTotalSizeInProgress(Collection<ProgressInfo> files)
+ private long getTotalSizeInProgress(Collection<ProgressInfo> streams)
{
long total = 0;
- for (ProgressInfo file : files)
- total += file.currentBytes;
+ for (ProgressInfo stream : streams)
+ total += stream.currentBytes;
return total;
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamCoordinator.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamCoordinator.java b/src/java/org/apache/cassandra/streaming/StreamCoordinator.java
index a22e07d..139488d 100644
--- a/src/java/org/apache/cassandra/streaming/StreamCoordinator.java
+++ b/src/java/org/apache/cassandra/streaming/StreamCoordinator.java
@@ -46,18 +46,18 @@ public class StreamCoordinator
private final boolean connectSequentially;
private Map<InetAddressAndPort, HostStreamingData> peerSessions = new HashMap<>();
+ private final StreamOperation streamOperation;
private final int connectionsPerHost;
private StreamConnectionFactory factory;
- private final boolean keepSSTableLevel;
private Iterator<StreamSession> sessionsToConnect = null;
private final UUID pendingRepair;
private final PreviewKind previewKind;
- public StreamCoordinator(int connectionsPerHost, boolean keepSSTableLevel, StreamConnectionFactory factory,
+ public StreamCoordinator(StreamOperation streamOperation, int connectionsPerHost, StreamConnectionFactory factory,
boolean connectSequentially, UUID pendingRepair, PreviewKind previewKind)
{
+ this.streamOperation = streamOperation;
this.connectionsPerHost = connectionsPerHost;
- this.keepSSTableLevel = keepSSTableLevel;
this.factory = factory;
this.connectSequentially = connectSequentially;
this.pendingRepair = pendingRepair;
@@ -191,51 +191,47 @@ public class StreamCoordinator
return result;
}
- public synchronized void transferFiles(InetAddressAndPort to, Collection<StreamSession.SSTableStreamingSections> sstableDetails)
+ public synchronized void transferStreams(InetAddressAndPort to, Collection<OutgoingStream> streams)
{
HostStreamingData sessionList = getOrCreateHostData(to);
if (connectionsPerHost > 1)
{
- List<List<StreamSession.SSTableStreamingSections>> buckets = sliceSSTableDetails(sstableDetails);
+ List<Collection<OutgoingStream>> buckets = bucketStreams(streams);
- for (List<StreamSession.SSTableStreamingSections> subList : buckets)
+ for (Collection<OutgoingStream> bucket : buckets)
{
StreamSession session = sessionList.getOrCreateNextSession(to, to);
- session.addTransferFiles(subList);
+ session.addTransferStreams(bucket);
}
}
else
{
StreamSession session = sessionList.getOrCreateNextSession(to, to);
- session.addTransferFiles(sstableDetails);
+ session.addTransferStreams(streams);
}
}
- private List<List<StreamSession.SSTableStreamingSections>> sliceSSTableDetails(Collection<StreamSession.SSTableStreamingSections> sstableDetails)
+ private List<Collection<OutgoingStream>> bucketStreams(Collection<OutgoingStream> streams)
{
// There's no point in divvying things up into more buckets than we have sstableDetails
- int targetSlices = Math.min(sstableDetails.size(), connectionsPerHost);
- int step = Math.round((float) sstableDetails.size() / (float) targetSlices);
+ int targetSlices = Math.min(streams.size(), connectionsPerHost);
+ int step = Math.round((float) streams.size() / (float) targetSlices);
int index = 0;
- List<List<StreamSession.SSTableStreamingSections>> result = new ArrayList<>();
- List<StreamSession.SSTableStreamingSections> slice = null;
- Iterator<StreamSession.SSTableStreamingSections> iter = sstableDetails.iterator();
- while (iter.hasNext())
- {
- StreamSession.SSTableStreamingSections streamSession = iter.next();
+ List<Collection<OutgoingStream>> result = new ArrayList<>();
+ List<OutgoingStream> slice = null;
+ for (OutgoingStream stream: streams)
+ {
if (index % step == 0)
{
slice = new ArrayList<>();
result.add(slice);
}
- slice.add(streamSession);
+ slice.add(stream);
++index;
- iter.remove();
}
-
return result;
}
@@ -302,7 +298,7 @@ public class StreamCoordinator
// create
if (streamSessions.size() < connectionsPerHost)
{
- StreamSession session = new StreamSession(peer, connecting, factory, streamSessions.size(), keepSSTableLevel, pendingRepair, previewKind);
+ StreamSession session = new StreamSession(streamOperation, peer, connecting, factory, streamSessions.size(), pendingRepair, previewKind);
streamSessions.put(++lastReturned, session);
return session;
}
@@ -334,7 +330,7 @@ public class StreamCoordinator
StreamSession session = streamSessions.get(id);
if (session == null)
{
- session = new StreamSession(peer, connecting, factory, id, keepSSTableLevel, pendingRepair, previewKind);
+ session = new StreamSession(streamOperation, peer, connecting, factory, id, pendingRepair, previewKind);
streamSessions.put(id, session);
}
return session;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamHook.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamHook.java b/src/java/org/apache/cassandra/streaming/StreamHook.java
index d610297..86b5182 100644
--- a/src/java/org/apache/cassandra/streaming/StreamHook.java
+++ b/src/java/org/apache/cassandra/streaming/StreamHook.java
@@ -18,19 +18,17 @@
package org.apache.cassandra.streaming;
-import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.io.sstable.SSTableMultiWriter;
-import org.apache.cassandra.io.sstable.format.SSTableReader;
-import org.apache.cassandra.streaming.messages.OutgoingFileMessage;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.streaming.messages.OutgoingStreamMessage;
import org.apache.cassandra.utils.FBUtilities;
public interface StreamHook
{
public static final StreamHook instance = createHook();
- public OutgoingFileMessage reportOutgoingFile(StreamSession session, SSTableReader sstable, OutgoingFileMessage message);
+ public OutgoingStreamMessage reportOutgoingStream(StreamSession session, OutgoingStream stream, OutgoingStreamMessage message);
public void reportStreamFuture(StreamSession session, StreamResultFuture future);
- public void reportIncomingFile(ColumnFamilyStore cfs, SSTableMultiWriter writer, StreamSession session, int sequenceNumber);
+ public void reportIncomingStream(TableId tableId, IncomingStream stream, StreamSession session, int sequenceNumber);
static StreamHook createHook()
{
@@ -43,14 +41,14 @@ public interface StreamHook
{
return new StreamHook()
{
- public OutgoingFileMessage reportOutgoingFile(StreamSession session, SSTableReader sstable, OutgoingFileMessage message)
+ public OutgoingStreamMessage reportOutgoingStream(StreamSession session, OutgoingStream stream, OutgoingStreamMessage message)
{
return message;
}
public void reportStreamFuture(StreamSession session, StreamResultFuture future) {}
- public void reportIncomingFile(ColumnFamilyStore cfs, SSTableMultiWriter writer, StreamSession session, int sequenceNumber) {}
+ public void reportIncomingStream(TableId tableId, IncomingStream stream, StreamSession session, int sequenceNumber) {}
};
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamPlan.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamPlan.java b/src/java/org/apache/cassandra/streaming/StreamPlan.java
index 43e9068..98d68ce 100644
--- a/src/java/org/apache/cassandra/streaming/StreamPlan.java
+++ b/src/java/org/apache/cassandra/streaming/StreamPlan.java
@@ -48,19 +48,19 @@ public class StreamPlan
*/
public StreamPlan(StreamOperation streamOperation)
{
- this(streamOperation, 1, false, false, NO_PENDING_REPAIR, PreviewKind.NONE);
+ this(streamOperation, 1, false, NO_PENDING_REPAIR, PreviewKind.NONE);
}
- public StreamPlan(StreamOperation streamOperation, boolean keepSSTableLevels, boolean connectSequentially)
+ public StreamPlan(StreamOperation streamOperation, boolean connectSequentially)
{
- this(streamOperation, 1, keepSSTableLevels, connectSequentially, NO_PENDING_REPAIR, PreviewKind.NONE);
+ this(streamOperation, 1, connectSequentially, NO_PENDING_REPAIR, PreviewKind.NONE);
}
- public StreamPlan(StreamOperation streamOperation, int connectionsPerHost, boolean keepSSTableLevels,
+ public StreamPlan(StreamOperation streamOperation, int connectionsPerHost,
boolean connectSequentially, UUID pendingRepair, PreviewKind previewKind)
{
this.streamOperation = streamOperation;
- this.coordinator = new StreamCoordinator(connectionsPerHost, keepSSTableLevels, new DefaultConnectionFactory(),
+ this.coordinator = new StreamCoordinator(streamOperation, connectionsPerHost, new DefaultConnectionFactory(),
connectSequentially, pendingRepair, previewKind);
}
@@ -137,18 +137,16 @@ public class StreamPlan
}
/**
- * Add transfer task to send given SSTable files.
+ * Add transfer task to send given streams
*
* @param to endpoint address of receiver
- * @param sstableDetails sstables with file positions and estimated key count.
- * this collection will be modified to remove those files that are successfully handed off
+ * @param streams streams to send
* @return this object for chaining
*/
- public StreamPlan transferFiles(InetAddressAndPort to, Collection<StreamSession.SSTableStreamingSections> sstableDetails)
+ public StreamPlan transferStreams(InetAddressAndPort to, Collection<OutgoingStream> streams)
{
- coordinator.transferFiles(to, sstableDetails);
+ coordinator.transferStreams(to, streams);
return this;
-
}
public StreamPlan listeners(StreamEventHandler handler, StreamEventHandler... handlers)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamReader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamReader.java b/src/java/org/apache/cassandra/streaming/StreamReader.java
deleted file mode 100644
index f4eb9c4..0000000
--- a/src/java/org/apache/cassandra/streaming/StreamReader.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming;
-
-import java.io.*;
-import java.util.Collection;
-import java.util.UUID;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.collect.UnmodifiableIterator;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.cassandra.io.util.TrackedDataInputPlus;
-import org.apache.cassandra.schema.TableId;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.db.*;
-import org.apache.cassandra.db.rows.*;
-import org.apache.cassandra.io.sstable.SSTableMultiWriter;
-import org.apache.cassandra.io.sstable.SSTableSimpleIterator;
-import org.apache.cassandra.io.sstable.format.RangeAwareSSTableWriter;
-import org.apache.cassandra.io.sstable.format.SSTableFormat;
-import org.apache.cassandra.io.sstable.format.Version;
-import org.apache.cassandra.io.util.DataInputPlus;
-import org.apache.cassandra.streaming.compress.StreamCompressionInputStream;
-import org.apache.cassandra.streaming.messages.FileMessageHeader;
-import org.apache.cassandra.streaming.messages.StreamMessage;
-import org.apache.cassandra.utils.ByteBufferUtil;
-import org.apache.cassandra.utils.FBUtilities;
-import org.apache.cassandra.utils.Pair;
-
-/**
- * StreamReader reads from stream and writes to SSTable.
- */
-public class StreamReader
-{
- private static final Logger logger = LoggerFactory.getLogger(StreamReader.class);
- protected final TableId tableId;
- protected final long estimatedKeys;
- protected final Collection<Pair<Long, Long>> sections;
- protected final StreamSession session;
- protected final Version inputVersion;
- protected final long repairedAt;
- protected final UUID pendingRepair;
- protected final SSTableFormat.Type format;
- protected final int sstableLevel;
- protected final SerializationHeader.Component header;
- protected final int fileSeqNum;
-
- public StreamReader(FileMessageHeader header, StreamSession session)
- {
- if (session.getPendingRepair() != null)
- {
- // we should only ever be streaming pending repair
- // sstables if the session has a pending repair id
- assert session.getPendingRepair().equals(header.pendingRepair);
- }
- this.session = session;
- this.tableId = header.tableId;
- this.estimatedKeys = header.estimatedKeys;
- this.sections = header.sections;
- this.inputVersion = header.version;
- this.repairedAt = header.repairedAt;
- this.pendingRepair = header.pendingRepair;
- this.format = header.format;
- this.sstableLevel = header.sstableLevel;
- this.header = header.header;
- this.fileSeqNum = header.sequenceNumber;
- }
-
- /**
- * @param inputPlus where this reads data from
- * @return SSTable transferred
- * @throws IOException if reading the remote sstable fails. Will throw an RTE if local write fails.
- */
- @SuppressWarnings("resource") // input needs to remain open, streams on top of it can't be closed
- public SSTableMultiWriter read(DataInputPlus inputPlus) throws IOException
- {
- long totalSize = totalSize();
-
- ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(tableId);
- if (cfs == null)
- {
- // schema was dropped during streaming
- throw new IOException("CF " + tableId + " was dropped during streaming");
- }
-
- logger.debug("[Stream #{}] Start receiving file #{} from {}, repairedAt = {}, size = {}, ks = '{}', table = '{}', pendingRepair = '{}'.",
- session.planId(), fileSeqNum, session.peer, repairedAt, totalSize, cfs.keyspace.getName(),
- cfs.getTableName(), pendingRepair);
-
- StreamDeserializer deserializer = null;
- SSTableMultiWriter writer = null;
- try (StreamCompressionInputStream streamCompressionInputStream = new StreamCompressionInputStream(inputPlus, StreamMessage.CURRENT_VERSION))
- {
- TrackedDataInputPlus in = new TrackedDataInputPlus(streamCompressionInputStream);
- deserializer = new StreamDeserializer(cfs.metadata(), in, inputVersion, getHeader(cfs.metadata()));
- writer = createWriter(cfs, totalSize, repairedAt, pendingRepair, format);
- while (in.getBytesRead() < totalSize)
- {
- writePartition(deserializer, writer);
- // TODO move this to BytesReadTracker
- session.progress(writer.getFilename(), ProgressInfo.Direction.IN, in.getBytesRead(), totalSize);
- }
- logger.debug("[Stream #{}] Finished receiving file #{} from {} readBytes = {}, totalSize = {}",
- session.planId(), fileSeqNum, session.peer, FBUtilities.prettyPrintMemory(in.getBytesRead()), FBUtilities.prettyPrintMemory(totalSize));
- return writer;
- }
- catch (Throwable e)
- {
- Object partitionKey = deserializer != null ? deserializer.partitionKey() : "";
- logger.warn("[Stream {}] Error while reading partition {} from stream on ks='{}' and table='{}'.",
- session.planId(), partitionKey, cfs.keyspace.getName(), cfs.getTableName(), e);
- if (writer != null)
- {
- writer.abort(e);
- }
- throw Throwables.propagate(e);
- }
- }
-
- protected SerializationHeader getHeader(TableMetadata metadata)
- {
- return header != null? header.toHeader(metadata) : null; //pre-3.0 sstable have no SerializationHeader
- }
-
- protected SSTableMultiWriter createWriter(ColumnFamilyStore cfs, long totalSize, long repairedAt, UUID pendingRepair, SSTableFormat.Type format) throws IOException
- {
- Directories.DataDirectory localDir = cfs.getDirectories().getWriteableLocation(totalSize);
- if (localDir == null)
- throw new IOException(String.format("Insufficient disk space to store %s", FBUtilities.prettyPrintMemory(totalSize)));
-
- RangeAwareSSTableWriter writer = new RangeAwareSSTableWriter(cfs, estimatedKeys, repairedAt, pendingRepair, format, sstableLevel, totalSize, session.getTransaction(tableId), getHeader(cfs.metadata()));
- StreamHook.instance.reportIncomingFile(cfs, writer, session, fileSeqNum);
- return writer;
- }
-
- protected long totalSize()
- {
- long size = 0;
- for (Pair<Long, Long> section : sections)
- size += section.right - section.left;
- return size;
- }
-
- protected void writePartition(StreamDeserializer deserializer, SSTableMultiWriter writer) throws IOException
- {
- writer.append(deserializer.newPartition());
- deserializer.checkForExceptions();
- }
-
- public static class StreamDeserializer extends UnmodifiableIterator<Unfiltered> implements UnfilteredRowIterator
- {
- private final TableMetadata metadata;
- private final DataInputPlus in;
- private final SerializationHeader header;
- private final SerializationHelper helper;
-
- private DecoratedKey key;
- private DeletionTime partitionLevelDeletion;
- private SSTableSimpleIterator iterator;
- private Row staticRow;
- private IOException exception;
-
- public StreamDeserializer(TableMetadata metadata, DataInputPlus in, Version version, SerializationHeader header) throws IOException
- {
- this.metadata = metadata;
- this.in = in;
- this.helper = new SerializationHelper(metadata, version.correspondingMessagingVersion(), SerializationHelper.Flag.PRESERVE_SIZE);
- this.header = header;
- }
-
- public StreamDeserializer newPartition() throws IOException
- {
- key = metadata.partitioner.decorateKey(ByteBufferUtil.readWithShortLength(in));
- partitionLevelDeletion = DeletionTime.serializer.deserialize(in);
- iterator = SSTableSimpleIterator.create(metadata, in, header, helper, partitionLevelDeletion);
- staticRow = iterator.readStaticRow();
- return this;
- }
-
- public TableMetadata metadata()
- {
- return metadata;
- }
-
- public RegularAndStaticColumns columns()
- {
- // We don't know which columns we'll get so assume it can be all of them
- return metadata.regularAndStaticColumns();
- }
-
- public boolean isReverseOrder()
- {
- return false;
- }
-
- public DecoratedKey partitionKey()
- {
- return key;
- }
-
- public DeletionTime partitionLevelDeletion()
- {
- return partitionLevelDeletion;
- }
-
- public Row staticRow()
- {
- return staticRow;
- }
-
- public EncodingStats stats()
- {
- return header.stats();
- }
-
- public boolean hasNext()
- {
- try
- {
- return iterator.hasNext();
- }
- catch (IOError e)
- {
- if (e.getCause() != null && e.getCause() instanceof IOException)
- {
- exception = (IOException)e.getCause();
- return false;
- }
- throw e;
- }
- }
-
- public Unfiltered next()
- {
- // Note that in practice we know that IOException will be thrown by hasNext(), because that's
- // where the actual reading happens, so we don't bother catching RuntimeException here (contrarily
- // to what we do in hasNext)
- Unfiltered unfiltered = iterator.next();
- return metadata.isCounter() && unfiltered.kind() == Unfiltered.Kind.ROW
- ? maybeMarkLocalToBeCleared((Row) unfiltered)
- : unfiltered;
- }
-
- private Row maybeMarkLocalToBeCleared(Row row)
- {
- return metadata.isCounter() ? row.markCounterLocalToBeCleared() : row;
- }
-
- public void checkForExceptions() throws IOException
- {
- if (exception != null)
- throw exception;
- }
-
- public void close()
- {
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamReceiveTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamReceiveTask.java b/src/java/org/apache/cassandra/streaming/StreamReceiveTask.java
index b823311..49beba1 100644
--- a/src/java/org/apache/cassandra/streaming/StreamReceiveTask.java
+++ b/src/java/org/apache/cassandra/streaming/StreamReceiveTask.java
@@ -17,38 +17,16 @@
*/
package org.apache.cassandra.streaming;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.db.Keyspace;
-import org.apache.cassandra.db.Mutation;
-import org.apache.cassandra.db.compaction.OperationType;
-import org.apache.cassandra.db.filter.ColumnFilter;
-import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
-import org.apache.cassandra.db.partitions.PartitionUpdate;
-import org.apache.cassandra.db.rows.ThrottledUnfilteredIterator;
-import org.apache.cassandra.db.rows.UnfilteredRowIterator;
-import org.apache.cassandra.db.view.View;
-import org.apache.cassandra.dht.Bounds;
-import org.apache.cassandra.dht.Token;
-import org.apache.cassandra.io.sstable.ISSTableScanner;
-import org.apache.cassandra.io.sstable.SSTableMultiWriter;
-import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.TableId;
-import org.apache.cassandra.utils.CloseableIterator;
import org.apache.cassandra.utils.JVMStabilityInspector;
-import org.apache.cassandra.utils.Throwables;
-import org.apache.cassandra.utils.concurrent.Refs;
/**
* Task that manages receiving files for the session for certain ColumnFamily.
@@ -59,69 +37,51 @@ public class StreamReceiveTask extends StreamTask
private static final ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("StreamReceiveTask"));
- private static final int MAX_ROWS_PER_BATCH = Integer.getInteger("cassandra.repair.mutation_repair_rows_per_batch", 100);
+ private final StreamReceiver receiver;
- // number of files to receive
- private final int totalFiles;
- // total size of files to receive
- private final long totalSize;
+ // number of streams to receive
+ private final int totalStreams;
- // Transaction tracking new files received
- private final LifecycleTransaction txn;
+ // total size of streams to receive
+ private final long totalSize;
// true if task is done (either completed or aborted)
private volatile boolean done = false;
- // holds references to SSTables received
- protected Collection<SSTableReader> sstables;
-
- private int remoteSSTablesReceived = 0;
+ private int remoteStreamsReceived = 0;
- public StreamReceiveTask(StreamSession session, TableId tableId, int totalFiles, long totalSize)
+ public StreamReceiveTask(StreamSession session, TableId tableId, int totalStreams, long totalSize)
{
super(session, tableId);
- this.totalFiles = totalFiles;
+ this.receiver = ColumnFamilyStore.getIfExists(tableId).getStreamManager().createStreamReceiver(session, totalStreams);
+ this.totalStreams = totalStreams;
this.totalSize = totalSize;
- // this is an "offline" transaction, as we currently manually expose the sstables once done;
- // this should be revisited at a later date, so that LifecycleTransaction manages all sstable state changes
- this.txn = LifecycleTransaction.offline(OperationType.STREAM);
- this.sstables = new ArrayList<>(totalFiles);
}
/**
- * Process received file.
+ * Process received stream.
*
- * @param sstable SSTable file received.
+ * @param stream Stream received.
*/
- public synchronized void received(SSTableMultiWriter sstable)
+ public synchronized void received(IncomingStream stream)
{
Preconditions.checkState(!session.isPreview(), "we should never receive sstables when previewing");
if (done)
{
- logger.warn("[{}] Received sstable {} on already finished stream received task. Aborting sstable.", session.planId(),
- sstable.getFilename());
- Throwables.maybeFail(sstable.abort(null));
+ logger.warn("[{}] Received stream {} on already finished stream received task. Aborting stream.", session.planId(),
+ stream.getName());
+ receiver.discardStream(stream);
return;
}
- remoteSSTablesReceived++;
- assert tableId.equals(sstable.getTableId());
- logger.debug("recevied {} of {} total files", remoteSSTablesReceived, totalFiles);
+ remoteStreamsReceived++;
+ Preconditions.checkArgument(tableId.equals(stream.getTableId()));
+ logger.debug("recevied {} of {} total files", remoteStreamsReceived, totalStreams);
- Collection<SSTableReader> finished = null;
- try
- {
- finished = sstable.finish(true);
- }
- catch (Throwable t)
- {
- Throwables.maybeFail(sstable.abort(t));
- }
- txn.update(finished, false);
- sstables.addAll(finished);
+ receiver.received(stream);
- if (remoteSSTablesReceived == totalFiles)
+ if (remoteStreamsReceived == totalStreams)
{
done = true;
executor.submit(new OnCompletionRunnable(this));
@@ -130,7 +90,7 @@ public class StreamReceiveTask extends StreamTask
public int getTotalNumberOfFiles()
{
- return totalFiles;
+ return totalStreams;
}
public long getTotalSize()
@@ -138,11 +98,11 @@ public class StreamReceiveTask extends StreamTask
return totalSize;
}
- public synchronized LifecycleTransaction getTransaction()
+ public synchronized StreamReceiver getReceiver()
{
if (done)
throw new RuntimeException(String.format("Stream receive task %s of cf %s already finished.", session.planId(), tableId));
- return txn;
+ return receiver;
}
private static class OnCompletionRunnable implements Runnable
@@ -154,116 +114,19 @@ public class StreamReceiveTask extends StreamTask
this.task = task;
}
- /*
- * We have a special path for views and for CDC.
- *
- * For views, since the view requires cleaning up any pre-existing state, we must put all partitions
- * through the same write path as normal mutations. This also ensures any 2is are also updated.
- *
- * For CDC-enabled tables, we want to ensure that the mutations are run through the CommitLog so they
- * can be archived by the CDC process on discard.
- */
- private boolean requiresWritePath(ColumnFamilyStore cfs) {
- return hasCDC(cfs) || (task.session.streamOperation().requiresViewBuild() && hasViews(cfs));
- }
-
- private boolean hasViews(ColumnFamilyStore cfs)
- {
- return !Iterables.isEmpty(View.findAll(cfs.metadata.keyspace, cfs.getTableName()));
- }
-
- private boolean hasCDC(ColumnFamilyStore cfs)
- {
- return cfs.metadata().params.cdc;
- }
-
- private void sendThroughWritePath(ColumnFamilyStore cfs, Collection<SSTableReader> readers) {
- boolean hasCdc = hasCDC(cfs);
- ColumnFilter filter = ColumnFilter.all(cfs.metadata());
- for (SSTableReader reader : readers)
- {
- Keyspace ks = Keyspace.open(reader.getKeyspaceName());
- // When doing mutation-based repair we split each partition into smaller batches
- // ({@link Stream MAX_ROWS_PER_BATCH}) to avoid OOMing and generating heap pressure
- try (ISSTableScanner scanner = reader.getScanner();
- CloseableIterator<UnfilteredRowIterator> throttledPartitions = ThrottledUnfilteredIterator.throttle(scanner, MAX_ROWS_PER_BATCH))
- {
- while (throttledPartitions.hasNext())
- {
- // MV *can* be applied unsafe if there's no CDC on the CFS as we flush
- // before transaction is done.
- //
- // If the CFS has CDC, however, these updates need to be written to the CommitLog
- // so they get archived into the cdc_raw folder
- ks.apply(new Mutation(PartitionUpdate.fromIterator(throttledPartitions.next(), filter)),
- hasCdc,
- true,
- false);
- }
- }
- }
- }
-
public void run()
{
- ColumnFamilyStore cfs = null;
- boolean requiresWritePath = false;
try
{
- cfs = ColumnFamilyStore.getIfExists(task.tableId);
- if (cfs == null)
+ if (ColumnFamilyStore.getIfExists(task.tableId) == null)
{
// schema was dropped during streaming
- task.sstables.clear();
- task.abortTransaction();
+ task.receiver.abort();
task.session.taskCompleted(task);
return;
}
- requiresWritePath = requiresWritePath(cfs);
- Collection<SSTableReader> readers = task.sstables;
-
- try (Refs<SSTableReader> refs = Refs.ref(readers))
- {
- if (requiresWritePath)
- {
- sendThroughWritePath(cfs, readers);
- }
- else
- {
- task.finishTransaction();
-
- // add sstables (this will build secondary indexes too, see CASSANDRA-10130)
- logger.debug("[Stream #{}] Received {} sstables from {} ({})", task.session.planId(), readers.size(), task.session.peer, readers);
- cfs.addSSTables(readers);
-
- //invalidate row and counter cache
- if (cfs.isRowCacheEnabled() || cfs.metadata().isCounter())
- {
- List<Bounds<Token>> boundsToInvalidate = new ArrayList<>(readers.size());
- readers.forEach(sstable -> boundsToInvalidate.add(new Bounds<Token>(sstable.first.getToken(), sstable.last.getToken())));
- Set<Bounds<Token>> nonOverlappingBounds = Bounds.getNonOverlappingBounds(boundsToInvalidate);
-
- if (cfs.isRowCacheEnabled())
- {
- int invalidatedKeys = cfs.invalidateRowCache(nonOverlappingBounds);
- if (invalidatedKeys > 0)
- logger.debug("[Stream #{}] Invalidated {} row cache entries on table {}.{} after stream " +
- "receive task completed.", task.session.planId(), invalidatedKeys,
- cfs.keyspace.getName(), cfs.getTableName());
- }
-
- if (cfs.metadata().isCounter())
- {
- int invalidatedKeys = cfs.invalidateCounterCache(nonOverlappingBounds);
- if (invalidatedKeys > 0)
- logger.debug("[Stream #{}] Invalidated {} counter cache entries on table {}.{} after stream " +
- "receive task completed.", task.session.planId(), invalidatedKeys,
- cfs.keyspace.getName(), cfs.getTableName());
- }
- }
- }
- }
+ task.receiver.finished();;
task.session.taskCompleted(task);
}
catch (Throwable t)
@@ -273,14 +136,7 @@ public class StreamReceiveTask extends StreamTask
}
finally
{
- // We don't keep the streamed sstables since we've applied them manually so we abort the txn and delete
- // the streamed sstables.
- if (requiresWritePath)
- {
- if (cfs != null)
- cfs.forceBlockingFlush();
- task.abortTransaction();
- }
+ task.receiver.cleanup();
}
}
}
@@ -297,17 +153,6 @@ public class StreamReceiveTask extends StreamTask
return;
done = true;
- abortTransaction();
- sstables.clear();
- }
-
- private synchronized void abortTransaction()
- {
- txn.abort();
- }
-
- private synchronized void finishTransaction()
- {
- txn.finish();
+ receiver.abort();
}
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamReceiver.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamReceiver.java b/src/java/org/apache/cassandra/streaming/StreamReceiver.java
new file mode 100644
index 0000000..bc357ef
--- /dev/null
+++ b/src/java/org/apache/cassandra/streaming/StreamReceiver.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.streaming;
+
+/**
+ * StreamReceiver acts as a staging area for incoming data. Received data
+ * ends up here, and is kept separate from the live data until all streams
+ * for a session have been received successfully
+ */
+public interface StreamReceiver
+{
+ /**
+ * Called after we've finished receiving stream data. The data covered by the given stream should
+ * be kept isolated from the live dataset for it's table.
+ */
+ void received(IncomingStream stream);
+
+ /**
+ * This is called when we've received stream data we can't add to the received set for some reason,
+ * usually when we've received data for a session which has been closed. The data backing this stream
+ * should be deleted, and any resources associated with the given stream should be released.
+ */
+ void discardStream(IncomingStream stream);
+
+ /**
+ * Called when something went wrong with a stream session. All data associated with this receiver
+ * should be deleted, and any associated resources should be cleaned up
+ */
+ void abort();
+
+ /**
+ * Called when a stream session has succesfully completed. All stream data being held by this receiver
+ * should be added to the live data sets for their respective tables before this method returns.
+ */
+ void finished();
+
+ /**
+ * Called after finished has returned and we've sent any messages to other nodes. Mainly for
+ * signaling that mvs and cdc should cleanup.
+ */
+ void cleanup();
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamResultFuture.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamResultFuture.java b/src/java/org/apache/cassandra/streaming/StreamResultFuture.java
index 544f37f..3b11fb6 100644
--- a/src/java/org/apache/cassandra/streaming/StreamResultFuture.java
+++ b/src/java/org/apache/cassandra/streaming/StreamResultFuture.java
@@ -73,9 +73,9 @@ public final class StreamResultFuture extends AbstractFuture<StreamState>
set(getCurrentState());
}
- private StreamResultFuture(UUID planId, StreamOperation streamOperation, boolean keepSSTableLevels, UUID pendingRepair, PreviewKind previewKind)
+ private StreamResultFuture(UUID planId, StreamOperation streamOperation, UUID pendingRepair, PreviewKind previewKind)
{
- this(planId, streamOperation, new StreamCoordinator(0, keepSSTableLevels, new DefaultConnectionFactory(), false, pendingRepair, previewKind));
+ this(planId, streamOperation, new StreamCoordinator(streamOperation, 0, new DefaultConnectionFactory(), false, pendingRepair, previewKind));
}
static StreamResultFuture init(UUID planId, StreamOperation streamOperation, Collection<StreamEventHandler> listeners,
@@ -106,7 +106,6 @@ public final class StreamResultFuture extends AbstractFuture<StreamState>
StreamOperation streamOperation,
InetAddressAndPort from,
Channel channel,
- boolean keepSSTableLevel,
UUID pendingRepair,
PreviewKind previewKind)
{
@@ -116,7 +115,7 @@ public final class StreamResultFuture extends AbstractFuture<StreamState>
logger.info("[Stream #{} ID#{}] Creating new streaming plan for {}", planId, sessionIndex, streamOperation.getDescription());
// The main reason we create a StreamResultFuture on the receiving side is for JMX exposure.
- future = new StreamResultFuture(planId, streamOperation, keepSSTableLevel, pendingRepair, previewKind);
+ future = new StreamResultFuture(planId, streamOperation, pendingRepair, previewKind);
StreamManager.instance.registerReceiving(future);
}
future.attachConnection(from, sessionIndex, channel);
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
[2/5] cassandra git commit: Abstract streaming for pluggable storage
Posted by bd...@apache.org.
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/FileMessageHeader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/FileMessageHeader.java b/src/java/org/apache/cassandra/streaming/messages/FileMessageHeader.java
deleted file mode 100644
index 13a3358..0000000
--- a/src/java/org/apache/cassandra/streaming/messages/FileMessageHeader.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming.messages;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import org.apache.cassandra.db.SerializationHeader;
-import org.apache.cassandra.db.TypeSizes;
-import org.apache.cassandra.io.compress.CompressionMetadata;
-import org.apache.cassandra.io.sstable.format.SSTableFormat;
-import org.apache.cassandra.io.util.DataInputPlus;
-import org.apache.cassandra.io.util.DataOutputPlus;
-import org.apache.cassandra.io.sstable.format.Version;
-import org.apache.cassandra.locator.InetAddressAndPort;
-import org.apache.cassandra.net.CompactEndpointSerializationHelper;
-import org.apache.cassandra.net.MessagingService;
-import org.apache.cassandra.schema.TableId;
-import org.apache.cassandra.streaming.StreamSession;
-import org.apache.cassandra.streaming.compress.CompressionInfo;
-import org.apache.cassandra.utils.Pair;
-import org.apache.cassandra.utils.UUIDSerializer;
-
-/**
- * StreamingFileHeader is appended before sending actual data to describe what it's sending.
- */
-public class FileMessageHeader
-{
- public static FileMessageHeaderSerializer serializer = new FileMessageHeaderSerializer();
-
- public final TableId tableId;
- public UUID planId;
- public int sessionIndex;
- public final int sequenceNumber;
- /** SSTable version */
- public final Version version;
-
- /** SSTable format **/
- public final SSTableFormat.Type format;
- public final long estimatedKeys;
- public final List<Pair<Long, Long>> sections;
- /**
- * Compression info for SSTable to send. Can be null if SSTable is not compressed.
- * On sender, this field is always null to avoid holding large number of Chunks.
- * Use compressionMetadata instead.
- */
- public final CompressionInfo compressionInfo;
- private final CompressionMetadata compressionMetadata;
- public final long repairedAt;
- public final UUID pendingRepair;
- public final int sstableLevel;
- public final SerializationHeader.Component header;
- public final InetAddressAndPort sender;
-
- /* cached size value */
- private transient final long size;
-
- private FileMessageHeader(TableId tableId,
- InetAddressAndPort sender,
- UUID planId,
- int sessionIndex,
- int sequenceNumber,
- Version version,
- SSTableFormat.Type format,
- long estimatedKeys,
- List<Pair<Long, Long>> sections,
- CompressionInfo compressionInfo,
- long repairedAt,
- UUID pendingRepair,
- int sstableLevel,
- SerializationHeader.Component header)
- {
- this.tableId = tableId;
- this.sender = sender;
- this.planId = planId;
- this.sessionIndex = sessionIndex;
- this.sequenceNumber = sequenceNumber;
- this.version = version;
- this.format = format;
- this.estimatedKeys = estimatedKeys;
- this.sections = sections;
- this.compressionInfo = compressionInfo;
- this.compressionMetadata = null;
- this.repairedAt = repairedAt;
- this.pendingRepair = pendingRepair;
- this.sstableLevel = sstableLevel;
- this.header = header;
- this.size = calculateSize();
- }
-
- public FileMessageHeader(TableId tableId,
- InetAddressAndPort sender,
- UUID planId,
- int sessionIndex,
- int sequenceNumber,
- Version version,
- SSTableFormat.Type format,
- long estimatedKeys,
- List<Pair<Long, Long>> sections,
- CompressionMetadata compressionMetadata,
- long repairedAt,
- UUID pendingRepair,
- int sstableLevel,
- SerializationHeader.Component header)
- {
- this.tableId = tableId;
- this.sender = sender;
- this.planId = planId;
- this.sessionIndex = sessionIndex;
- this.sequenceNumber = sequenceNumber;
- this.version = version;
- this.format = format;
- this.estimatedKeys = estimatedKeys;
- this.sections = sections;
- this.compressionInfo = null;
- this.compressionMetadata = compressionMetadata;
- this.repairedAt = repairedAt;
- this.pendingRepair = pendingRepair;
- this.sstableLevel = sstableLevel;
- this.header = header;
- this.size = calculateSize();
- }
-
- public boolean isCompressed()
- {
- return compressionInfo != null || compressionMetadata != null;
- }
-
- /**
- * @return total file size to transfer in bytes
- */
- public long size()
- {
- return size;
- }
-
- private long calculateSize()
- {
- long transferSize = 0;
- if (compressionInfo != null)
- {
- // calculate total length of transferring chunks
- for (CompressionMetadata.Chunk chunk : compressionInfo.chunks)
- transferSize += chunk.length + 4; // 4 bytes for CRC
- }
- else if (compressionMetadata != null)
- {
- transferSize = compressionMetadata.getTotalSizeForSections(sections);
- }
- else
- {
- for (Pair<Long, Long> section : sections)
- transferSize += section.right - section.left;
- }
- return transferSize;
- }
-
- @Override
- public String toString()
- {
- final StringBuilder sb = new StringBuilder("Header (");
- sb.append("tableId: ").append(tableId);
- sb.append(", #").append(sequenceNumber);
- sb.append(", version: ").append(version);
- sb.append(", format: ").append(format);
- sb.append(", estimated keys: ").append(estimatedKeys);
- sb.append(", transfer size: ").append(size());
- sb.append(", compressed?: ").append(isCompressed());
- sb.append(", repairedAt: ").append(repairedAt);
- sb.append(", pendingRepair: ").append(pendingRepair);
- sb.append(", level: ").append(sstableLevel);
- sb.append(')');
- return sb.toString();
- }
-
- @Override
- public boolean equals(Object o)
- {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- FileMessageHeader that = (FileMessageHeader) o;
- return sequenceNumber == that.sequenceNumber && tableId.equals(that.tableId);
- }
-
- @Override
- public int hashCode()
- {
- int result = tableId.hashCode();
- result = 31 * result + sequenceNumber;
- return result;
- }
-
- public void addSessionInfo(StreamSession session)
- {
- planId = session.planId();
- sessionIndex = session.sessionIndex();
- }
-
- static class FileMessageHeaderSerializer
- {
- public CompressionInfo serialize(FileMessageHeader header, DataOutputPlus out, int version) throws IOException
- {
- header.tableId.serialize(out);
- CompactEndpointSerializationHelper.streamingInstance.serialize(header.sender, out, version);
- UUIDSerializer.serializer.serialize(header.planId, out, version);
- out.writeInt(header.sessionIndex);
- out.writeInt(header.sequenceNumber);
- out.writeUTF(header.version.toString());
- out.writeUTF(header.format.name);
-
- out.writeLong(header.estimatedKeys);
- out.writeInt(header.sections.size());
- for (Pair<Long, Long> section : header.sections)
- {
- out.writeLong(section.left);
- out.writeLong(section.right);
- }
- // construct CompressionInfo here to avoid holding large number of Chunks on heap.
- CompressionInfo compressionInfo = null;
- if (header.compressionMetadata != null)
- compressionInfo = new CompressionInfo(header.compressionMetadata.getChunksForSections(header.sections), header.compressionMetadata.parameters);
- CompressionInfo.serializer.serialize(compressionInfo, out, version);
- out.writeLong(header.repairedAt);
- out.writeBoolean(header.pendingRepair != null);
- if (header.pendingRepair != null)
- {
- UUIDSerializer.serializer.serialize(header.pendingRepair, out, version);
- }
- out.writeInt(header.sstableLevel);
-
- SerializationHeader.serializer.serialize(header.version, header.header, out);
- return compressionInfo;
- }
-
- public FileMessageHeader deserialize(DataInputPlus in, int version) throws IOException
- {
- TableId tableId = TableId.deserialize(in);
- InetAddressAndPort sender = CompactEndpointSerializationHelper.streamingInstance.deserialize(in, version);
- UUID planId = UUIDSerializer.serializer.deserialize(in, MessagingService.current_version);
- int sessionIndex = in.readInt();
- int sequenceNumber = in.readInt();
- Version sstableVersion = SSTableFormat.Type.current().info.getVersion(in.readUTF());
- SSTableFormat.Type format = SSTableFormat.Type.validate(in.readUTF());
-
- long estimatedKeys = in.readLong();
- int count = in.readInt();
- List<Pair<Long, Long>> sections = new ArrayList<>(count);
- for (int k = 0; k < count; k++)
- sections.add(Pair.create(in.readLong(), in.readLong()));
- CompressionInfo compressionInfo = CompressionInfo.serializer.deserialize(in, version);
- long repairedAt = in.readLong();
- UUID pendingRepair = in.readBoolean() ? UUIDSerializer.serializer.deserialize(in, version) : null;
- int sstableLevel = in.readInt();
- SerializationHeader.Component header = SerializationHeader.serializer.deserialize(sstableVersion, in);
-
- return new FileMessageHeader(tableId, sender, planId, sessionIndex, sequenceNumber, sstableVersion, format, estimatedKeys, sections, compressionInfo, repairedAt, pendingRepair, sstableLevel, header);
- }
-
- public long serializedSize(FileMessageHeader header, int version)
- {
- long size = header.tableId.serializedSize();
- size += CompactEndpointSerializationHelper.streamingInstance.serializedSize(header.sender, version);
- size += UUIDSerializer.serializer.serializedSize(header.planId, version);
- size += TypeSizes.sizeof(header.sessionIndex);
- size += TypeSizes.sizeof(header.sequenceNumber);
- size += TypeSizes.sizeof(header.version.toString());
- size += TypeSizes.sizeof(header.format.name);
- size += TypeSizes.sizeof(header.estimatedKeys);
-
- size += TypeSizes.sizeof(header.sections.size());
- for (Pair<Long, Long> section : header.sections)
- {
- size += TypeSizes.sizeof(section.left);
- size += TypeSizes.sizeof(section.right);
- }
- size += CompressionInfo.serializer.serializedSize(header.compressionInfo, version);
- size += TypeSizes.sizeof(header.repairedAt);
- size += TypeSizes.sizeof(header.pendingRepair != null);
- size += header.pendingRepair != null ? UUIDSerializer.serializer.serializedSize(header.pendingRepair, version) : 0;
- size += TypeSizes.sizeof(header.sstableLevel);
-
- size += SerializationHeader.serializer.serializedSize(header.version, header.header);
-
- return size;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/IncomingFileMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/IncomingFileMessage.java b/src/java/org/apache/cassandra/streaming/messages/IncomingFileMessage.java
deleted file mode 100644
index 9f43982..0000000
--- a/src/java/org/apache/cassandra/streaming/messages/IncomingFileMessage.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming.messages;
-
-import java.io.IOException;
-
-import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.io.sstable.SSTableMultiWriter;
-import org.apache.cassandra.io.util.DataInputPlus;
-
-import org.apache.cassandra.io.util.DataOutputStreamPlus;
-import org.apache.cassandra.streaming.StreamManager;
-import org.apache.cassandra.streaming.StreamReader;
-import org.apache.cassandra.streaming.StreamReceiveException;
-import org.apache.cassandra.streaming.StreamSession;
-import org.apache.cassandra.streaming.compress.CompressedStreamReader;
-import org.apache.cassandra.utils.JVMStabilityInspector;
-
-
-/**
- * IncomingFileMessage is used to receive the part(or whole) of a SSTable data file.
- */
-public class IncomingFileMessage extends StreamMessage
-{
- public static Serializer<IncomingFileMessage> serializer = new Serializer<IncomingFileMessage>()
- {
- @SuppressWarnings("resource")
- public IncomingFileMessage deserialize(DataInputPlus input, int version, StreamSession session) throws IOException
- {
- FileMessageHeader header = FileMessageHeader.serializer.deserialize(input, version);
- session = StreamManager.instance.findSession(header.sender, header.planId, header.sessionIndex);
- if (session == null)
- throw new IllegalStateException(String.format("unknown stream session: %s - %d", header.planId, header.sessionIndex));
- ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(header.tableId);
- if (cfs == null)
- throw new StreamReceiveException(session, "CF " + header.tableId + " was dropped during streaming");
-
- StreamReader reader = !header.isCompressed() ? new StreamReader(header, session)
- : new CompressedStreamReader(header, session);
-
- try
- {
- return new IncomingFileMessage(reader.read(input), header);
- }
- catch (Throwable t)
- {
- JVMStabilityInspector.inspectThrowable(t);
- throw new StreamReceiveException(session, t);
- }
- }
-
- public void serialize(IncomingFileMessage message, DataOutputStreamPlus out, int version, StreamSession session)
- {
- throw new UnsupportedOperationException("Not allowed to call serialize on an incoming file");
- }
-
- public long serializedSize(IncomingFileMessage message, int version)
- {
- throw new UnsupportedOperationException("Not allowed to call serializedSize on an incoming file");
- }
- };
-
- public FileMessageHeader header;
- public SSTableMultiWriter sstable;
-
- public IncomingFileMessage(SSTableMultiWriter sstable, FileMessageHeader header)
- {
- super(Type.FILE);
- this.header = header;
- this.sstable = sstable;
- }
-
- @Override
- public String toString()
- {
- String filename = sstable != null ? sstable.getFilename() : null;
- return "File (" + header + ", file: " + filename + ")";
- }
-}
-
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/IncomingStreamMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/IncomingStreamMessage.java b/src/java/org/apache/cassandra/streaming/messages/IncomingStreamMessage.java
new file mode 100644
index 0000000..e17c3ab
--- /dev/null
+++ b/src/java/org/apache/cassandra/streaming/messages/IncomingStreamMessage.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.streaming.messages;
+
+import java.io.IOException;
+import java.util.Objects;
+
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.io.util.DataInputPlus;
+
+import org.apache.cassandra.io.util.DataOutputStreamPlus;
+import org.apache.cassandra.streaming.IncomingStream;
+import org.apache.cassandra.streaming.StreamManager;
+import org.apache.cassandra.streaming.StreamReceiveException;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.utils.JVMStabilityInspector;
+
+public class IncomingStreamMessage extends StreamMessage
+{
+ public static Serializer<IncomingStreamMessage> serializer = new Serializer<IncomingStreamMessage>()
+ {
+ @SuppressWarnings("resource")
+ public IncomingStreamMessage deserialize(DataInputPlus input, int version, StreamSession session) throws IOException
+ {
+ StreamMessageHeader header = StreamMessageHeader.serializer.deserialize(input, version);
+ session = StreamManager.instance.findSession(header.sender, header.planId, header.sessionIndex);
+ if (session == null)
+ throw new IllegalStateException(String.format("unknown stream session: %s - %d", header.planId, header.sessionIndex));
+ ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(header.tableId);
+ if (cfs == null)
+ throw new StreamReceiveException(session, "CF " + header.tableId + " was dropped during streaming");
+
+ IncomingStream incomingData = cfs.getStreamManager().prepareIncomingStream(session, header);
+ incomingData.read(input, version);
+
+ try
+ {
+ return new IncomingStreamMessage(incomingData, header);
+ }
+ catch (Throwable t)
+ {
+ JVMStabilityInspector.inspectThrowable(t);
+ throw new StreamReceiveException(session, t);
+ }
+ }
+
+ public void serialize(IncomingStreamMessage message, DataOutputStreamPlus out, int version, StreamSession session)
+ {
+ throw new UnsupportedOperationException("Not allowed to call serialize on an incoming stream");
+ }
+
+ public long serializedSize(IncomingStreamMessage message, int version)
+ {
+ throw new UnsupportedOperationException("Not allowed to call serializedSize on an incoming stream");
+ }
+ };
+
+ public StreamMessageHeader header;
+ public IncomingStream stream;
+
+ public IncomingStreamMessage(IncomingStream stream, StreamMessageHeader header)
+ {
+ super(Type.STREAM);
+ this.stream = stream;
+ this.header = header;
+ }
+
+ @Override
+ public String toString()
+ {
+ return "IncomingStreamMessage{" +
+ "header=" + header +
+ ", stream=" + stream +
+ '}';
+ }
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ IncomingStreamMessage that = (IncomingStreamMessage) o;
+ return Objects.equals(header, that.header) &&
+ Objects.equals(stream, that.stream);
+ }
+
+ public int hashCode()
+ {
+
+ return Objects.hash(header, stream);
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java b/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
deleted file mode 100644
index 8bbcc05..0000000
--- a/src/java/org/apache/cassandra/streaming/messages/OutgoingFileMessage.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming.messages;
-
-import java.io.IOException;
-import java.util.List;
-
-import com.google.common.annotations.VisibleForTesting;
-
-import org.apache.cassandra.io.sstable.format.SSTableReader;
-import org.apache.cassandra.io.util.DataInputPlus;
-import org.apache.cassandra.io.util.DataOutputStreamPlus;
-import org.apache.cassandra.streaming.StreamSession;
-import org.apache.cassandra.streaming.StreamWriter;
-import org.apache.cassandra.streaming.compress.CompressedStreamWriter;
-import org.apache.cassandra.streaming.compress.CompressionInfo;
-import org.apache.cassandra.utils.FBUtilities;
-import org.apache.cassandra.utils.Pair;
-import org.apache.cassandra.utils.concurrent.Ref;
-
-/**
- * OutgoingFileMessage is used to transfer the part(or whole) of a SSTable data file.
- */
-public class OutgoingFileMessage extends StreamMessage
-{
- public static Serializer<OutgoingFileMessage> serializer = new Serializer<OutgoingFileMessage>()
- {
- public OutgoingFileMessage deserialize(DataInputPlus in, int version, StreamSession session)
- {
- throw new UnsupportedOperationException("Not allowed to call deserialize on an outgoing file");
- }
-
- public void serialize(OutgoingFileMessage message, DataOutputStreamPlus out, int version, StreamSession session) throws IOException
- {
- message.startTransfer();
- try
- {
- message.serialize(out, version, session);
- session.fileSent(message.header);
- }
- finally
- {
- message.finishTransfer();
- }
- }
-
- public long serializedSize(OutgoingFileMessage message, int version)
- {
- return 0;
- }
- };
-
- public final FileMessageHeader header;
- private final Ref<SSTableReader> ref;
- private final String filename;
- private boolean completed = false;
- private boolean transferring = false;
-
- public OutgoingFileMessage(Ref<SSTableReader> ref, StreamSession session, int sequenceNumber, long estimatedKeys, List<Pair<Long, Long>> sections, boolean keepSSTableLevel)
- {
- super(Type.FILE);
- this.ref = ref;
-
- SSTableReader sstable = ref.get();
- filename = sstable.getFilename();
- this.header = new FileMessageHeader(sstable.metadata().id,
- FBUtilities.getBroadcastAddressAndPort(),
- session.planId(),
- session.sessionIndex(),
- sequenceNumber,
- sstable.descriptor.version,
- sstable.descriptor.formatType,
- estimatedKeys,
- sections,
- sstable.compression ? sstable.getCompressionMetadata() : null,
- sstable.getRepairedAt(),
- sstable.getPendingRepair(),
- keepSSTableLevel ? sstable.getSSTableLevel() : 0,
- sstable.header.toComponent());
- }
-
- public synchronized void serialize(DataOutputStreamPlus out, int version, StreamSession session) throws IOException
- {
- if (completed)
- {
- return;
- }
-
- CompressionInfo compressionInfo = FileMessageHeader.serializer.serialize(header, out, version);
- out.flush();
- final SSTableReader reader = ref.get();
- StreamWriter writer = compressionInfo == null ?
- new StreamWriter(reader, header.sections, session) :
- new CompressedStreamWriter(reader, header.sections,
- compressionInfo, session);
- writer.write(out);
- }
-
- @VisibleForTesting
- public synchronized void finishTransfer()
- {
- transferring = false;
- //session was aborted mid-transfer, now it's safe to release
- if (completed)
- {
- ref.release();
- }
- }
-
- @VisibleForTesting
- public synchronized void startTransfer()
- {
- if (completed)
- throw new RuntimeException(String.format("Transfer of file %s already completed or aborted (perhaps session failed?).",
- filename));
- transferring = true;
- }
-
- public synchronized void complete()
- {
- if (!completed)
- {
- completed = true;
- //release only if not transferring
- if (!transferring)
- {
- ref.release();
- }
- }
- }
-
- @Override
- public String toString()
- {
- return "File (" + header + ", file: " + filename + ")";
- }
-
- public String getFilename()
- {
- return filename;
- }
-}
-
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/OutgoingStreamMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/OutgoingStreamMessage.java b/src/java/org/apache/cassandra/streaming/messages/OutgoingStreamMessage.java
new file mode 100644
index 0000000..263aabd
--- /dev/null
+++ b/src/java/org/apache/cassandra/streaming/messages/OutgoingStreamMessage.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.streaming.messages;
+
+import java.io.IOException;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.DataOutputStreamPlus;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.streaming.OutgoingStream;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.utils.FBUtilities;
+
+public class OutgoingStreamMessage extends StreamMessage
+{
+ public static Serializer<OutgoingStreamMessage> serializer = new Serializer<OutgoingStreamMessage>()
+ {
+ public OutgoingStreamMessage deserialize(DataInputPlus in, int version, StreamSession session)
+ {
+ throw new UnsupportedOperationException("Not allowed to call deserialize on an outgoing stream");
+ }
+
+ public void serialize(OutgoingStreamMessage message, DataOutputStreamPlus out, int version, StreamSession session) throws IOException
+ {
+ message.startTransfer();
+ try
+ {
+ message.serialize(out, version, session);
+ session.streamSent(message);
+ }
+ finally
+ {
+ message.finishTransfer();
+ }
+ }
+
+ public long serializedSize(OutgoingStreamMessage message, int version)
+ {
+ return 0;
+ }
+ };
+
+ public final StreamMessageHeader header;
+ private final TableId tableId;
+ public final OutgoingStream stream;
+ private boolean completed = false;
+ private boolean transferring = false;
+
+ public OutgoingStreamMessage(TableId tableId, StreamSession session, OutgoingStream stream, int sequenceNumber)
+ {
+ super(Type.STREAM);
+ this.tableId = tableId;
+
+ this.stream = stream;
+ this.header = new StreamMessageHeader(tableId,
+ FBUtilities.getBroadcastAddressAndPort(),
+ session.planId(),
+ session.sessionIndex(),
+ sequenceNumber,
+ stream.getRepairedAt(),
+ stream.getPendingRepair());
+ }
+
+ public synchronized void serialize(DataOutputStreamPlus out, int version, StreamSession session) throws IOException
+ {
+ if (completed)
+ {
+ return;
+ }
+ StreamMessageHeader.serializer.serialize(header, out, version);
+ stream.write(session, out, version);
+ }
+
+ @VisibleForTesting
+ public synchronized void finishTransfer()
+ {
+ transferring = false;
+ //session was aborted mid-transfer, now it's safe to release
+ if (completed)
+ {
+ stream.finish();
+ }
+ }
+
+ @VisibleForTesting
+ public synchronized void startTransfer()
+ {
+ if (completed)
+ throw new RuntimeException(String.format("Transfer of stream %s already completed or aborted (perhaps session failed?).",
+ stream));
+ transferring = true;
+ }
+
+ public synchronized void complete()
+ {
+ if (!completed)
+ {
+ completed = true;
+ //release only if not transferring
+ if (!transferring)
+ {
+ stream.finish();
+ }
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return "OutgoingStreamMessage{" +
+ "header=" + header +
+ ", stream=" + stream +
+ '}';
+ }
+
+ public String getName()
+ {
+ return stream.getName();
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/StreamInitMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/StreamInitMessage.java b/src/java/org/apache/cassandra/streaming/messages/StreamInitMessage.java
index fced133..fbd3e21 100644
--- a/src/java/org/apache/cassandra/streaming/messages/StreamInitMessage.java
+++ b/src/java/org/apache/cassandra/streaming/messages/StreamInitMessage.java
@@ -44,18 +44,16 @@ public class StreamInitMessage extends StreamMessage
public final UUID planId;
public final StreamOperation streamOperation;
- public final boolean keepSSTableLevel;
public final UUID pendingRepair;
public final PreviewKind previewKind;
- public StreamInitMessage(InetAddressAndPort from, int sessionIndex, UUID planId, StreamOperation streamOperation, boolean keepSSTableLevel, UUID pendingRepair, PreviewKind previewKind)
+ public StreamInitMessage(InetAddressAndPort from, int sessionIndex, UUID planId, StreamOperation streamOperation, UUID pendingRepair, PreviewKind previewKind)
{
super(Type.STREAM_INIT);
this.from = from;
this.sessionIndex = sessionIndex;
this.planId = planId;
this.streamOperation = streamOperation;
- this.keepSSTableLevel = keepSSTableLevel;
this.pendingRepair = pendingRepair;
this.previewKind = previewKind;
}
@@ -77,7 +75,6 @@ public class StreamInitMessage extends StreamMessage
out.writeInt(message.sessionIndex);
UUIDSerializer.serializer.serialize(message.planId, out, MessagingService.current_version);
out.writeUTF(message.streamOperation.getDescription());
- out.writeBoolean(message.keepSSTableLevel);
out.writeBoolean(message.pendingRepair != null);
if (message.pendingRepair != null)
@@ -93,11 +90,10 @@ public class StreamInitMessage extends StreamMessage
int sessionIndex = in.readInt();
UUID planId = UUIDSerializer.serializer.deserialize(in, MessagingService.current_version);
String description = in.readUTF();
- boolean keepSSTableLevel = in.readBoolean();
UUID pendingRepair = in.readBoolean() ? UUIDSerializer.serializer.deserialize(in, version) : null;
PreviewKind previewKind = PreviewKind.deserialize(in.readInt());
- return new StreamInitMessage(from, sessionIndex, planId, StreamOperation.fromString(description), keepSSTableLevel, pendingRepair, previewKind);
+ return new StreamInitMessage(from, sessionIndex, planId, StreamOperation.fromString(description), pendingRepair, previewKind);
}
public long serializedSize(StreamInitMessage message, int version)
@@ -106,7 +102,6 @@ public class StreamInitMessage extends StreamMessage
size += TypeSizes.sizeof(message.sessionIndex);
size += UUIDSerializer.serializer.serializedSize(message.planId, MessagingService.current_version);
size += TypeSizes.sizeof(message.streamOperation.getDescription());
- size += TypeSizes.sizeof(message.keepSSTableLevel);
size += TypeSizes.sizeof(message.pendingRepair != null);
if (message.pendingRepair != null)
{
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/StreamMessage.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/StreamMessage.java b/src/java/org/apache/cassandra/streaming/messages/StreamMessage.java
index feeab05..7ab3d34 100644
--- a/src/java/org/apache/cassandra/streaming/messages/StreamMessage.java
+++ b/src/java/org/apache/cassandra/streaming/messages/StreamMessage.java
@@ -67,7 +67,7 @@ public abstract class StreamMessage
public enum Type
{
PREPARE_SYN(1, 5, PrepareSynMessage.serializer),
- FILE(2, 0, IncomingFileMessage.serializer, OutgoingFileMessage.serializer),
+ STREAM(2, 0, IncomingStreamMessage.serializer, OutgoingStreamMessage.serializer),
RECEIVED(3, 4, ReceivedMessage.serializer),
COMPLETE(5, 1, CompleteMessage.serializer),
SESSION_FAILED(6, 5, SessionFailedMessage.serializer),
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/messages/StreamMessageHeader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/messages/StreamMessageHeader.java b/src/java/org/apache/cassandra/streaming/messages/StreamMessageHeader.java
new file mode 100644
index 0000000..84cf3a3
--- /dev/null
+++ b/src/java/org/apache/cassandra/streaming/messages/StreamMessageHeader.java
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cassandra.streaming.messages;
+
+import java.io.IOException;
+import java.util.UUID;
+
+import org.apache.cassandra.db.TypeSizes;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.DataOutputPlus;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.net.CompactEndpointSerializationHelper;
+import org.apache.cassandra.net.MessagingService;
+import org.apache.cassandra.schema.TableId;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.utils.UUIDSerializer;
+
+/**
+ * StreamingFileHeader is appended before sending actual data to describe what it's sending.
+ */
+public class StreamMessageHeader
+{
+ public static FileMessageHeaderSerializer serializer = new FileMessageHeaderSerializer();
+
+ public final TableId tableId;
+ public UUID planId;
+ public int sessionIndex;
+ public final int sequenceNumber;
+ public final long repairedAt;
+ public final UUID pendingRepair;
+ public final InetAddressAndPort sender;
+
+ public StreamMessageHeader(TableId tableId,
+ InetAddressAndPort sender,
+ UUID planId,
+ int sessionIndex,
+ int sequenceNumber,
+ long repairedAt,
+ UUID pendingRepair)
+ {
+ this.tableId = tableId;
+ this.sender = sender;
+ this.planId = planId;
+ this.sessionIndex = sessionIndex;
+ this.sequenceNumber = sequenceNumber;
+ this.repairedAt = repairedAt;
+ this.pendingRepair = pendingRepair;
+ }
+
+ @Override
+ public String toString()
+ {
+ final StringBuilder sb = new StringBuilder("Header (");
+ sb.append("tableId: ").append(tableId);
+ sb.append(", #").append(sequenceNumber);
+ sb.append(", repairedAt: ").append(repairedAt);
+ sb.append(", pendingRepair: ").append(pendingRepair);
+ sb.append(')');
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ StreamMessageHeader that = (StreamMessageHeader) o;
+ return sequenceNumber == that.sequenceNumber && tableId.equals(that.tableId);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ int result = tableId.hashCode();
+ result = 31 * result + sequenceNumber;
+ return result;
+ }
+
+ public void addSessionInfo(StreamSession session)
+ {
+ planId = session.planId();
+ sessionIndex = session.sessionIndex();
+ }
+
+ static class FileMessageHeaderSerializer
+ {
+ public void serialize(StreamMessageHeader header, DataOutputPlus out, int version) throws IOException
+ {
+ header.tableId.serialize(out);
+ CompactEndpointSerializationHelper.streamingInstance.serialize(header.sender, out, version);
+ UUIDSerializer.serializer.serialize(header.planId, out, version);
+ out.writeInt(header.sessionIndex);
+ out.writeInt(header.sequenceNumber);
+ out.writeLong(header.repairedAt);
+ out.writeBoolean(header.pendingRepair != null);
+ if (header.pendingRepair != null)
+ {
+ UUIDSerializer.serializer.serialize(header.pendingRepair, out, version);
+ }
+ }
+
+ public StreamMessageHeader deserialize(DataInputPlus in, int version) throws IOException
+ {
+ TableId tableId = TableId.deserialize(in);
+ InetAddressAndPort sender = CompactEndpointSerializationHelper.streamingInstance.deserialize(in, version);
+ UUID planId = UUIDSerializer.serializer.deserialize(in, MessagingService.current_version);
+ int sessionIndex = in.readInt();
+ int sequenceNumber = in.readInt();
+ long repairedAt = in.readLong();
+ UUID pendingRepair = in.readBoolean() ? UUIDSerializer.serializer.deserialize(in, version) : null;
+
+ return new StreamMessageHeader(tableId, sender, planId, sessionIndex, sequenceNumber, repairedAt, pendingRepair);
+ }
+
+ public long serializedSize(StreamMessageHeader header, int version)
+ {
+ long size = header.tableId.serializedSize();
+ size += CompactEndpointSerializationHelper.streamingInstance.serializedSize(header.sender, version);
+ size += UUIDSerializer.serializer.serializedSize(header.planId, version);
+ size += TypeSizes.sizeof(header.sessionIndex);
+ size += TypeSizes.sizeof(header.sequenceNumber);
+ size += TypeSizes.sizeof(header.repairedAt);
+ size += TypeSizes.sizeof(header.pendingRepair != null);
+ size += header.pendingRepair != null ? UUIDSerializer.serializer.serializedSize(header.pendingRepair, version) : 0;
+
+ return size;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/db/streaming/CassandraStreamHeaderTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/streaming/CassandraStreamHeaderTest.java b/test/unit/org/apache/cassandra/db/streaming/CassandraStreamHeaderTest.java
new file mode 100644
index 0000000..289bb0f
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/streaming/CassandraStreamHeaderTest.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db.streaming;
+
+import java.util.ArrayList;
+
+import org.junit.Test;
+
+import org.apache.cassandra.cql3.statements.CreateTableStatement;
+import org.apache.cassandra.db.SerializationHeader;
+import org.apache.cassandra.io.compress.CompressionMetadata;
+import org.apache.cassandra.io.sstable.format.SSTableFormat;
+import org.apache.cassandra.io.sstable.format.big.BigFormat;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.serializers.SerializationUtils;
+
+public class CassandraStreamHeaderTest
+{
+ @Test
+ public void serializerTest()
+ {
+ String ddl = "CREATE TABLE tbl (k INT PRIMARY KEY, v INT)";
+ TableMetadata metadata = CreateTableStatement.parse(ddl, "ks").build();
+ CassandraStreamHeader header = new CassandraStreamHeader(BigFormat.latestVersion,
+ SSTableFormat.Type.BIG,
+ 0,
+ new ArrayList<>(),
+ ((CompressionMetadata) null),
+ 0,
+ SerializationHeader.makeWithoutStats(metadata).toComponent());
+
+ SerializationUtils.assertSerializationCycle(header, CassandraStreamHeader.serializer);
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/db/streaming/CassandraStreamManagerTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/db/streaming/CassandraStreamManagerTest.java b/test/unit/org/apache/cassandra/db/streaming/CassandraStreamManagerTest.java
new file mode 100644
index 0000000..8497e71
--- /dev/null
+++ b/test/unit/org/apache/cassandra/db/streaming/CassandraStreamManagerTest.java
@@ -0,0 +1,237 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.db.streaming;
+
+import java.io.IOException;
+import java.net.UnknownHostException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Uninterruptibles;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import org.apache.cassandra.SchemaLoader;
+import org.apache.cassandra.concurrent.NamedThreadFactory;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.QueryProcessor;
+import org.apache.cassandra.cql3.statements.CreateTableStatement;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.dht.IPartitioner;
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+import org.apache.cassandra.locator.InetAddressAndPort;
+import org.apache.cassandra.schema.KeyspaceParams;
+import org.apache.cassandra.schema.Schema;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.streaming.DefaultConnectionFactory;
+import org.apache.cassandra.streaming.OutgoingStream;
+import org.apache.cassandra.streaming.PreviewKind;
+import org.apache.cassandra.streaming.StreamConnectionFactory;
+import org.apache.cassandra.streaming.StreamOperation;
+import org.apache.cassandra.streaming.StreamSession;
+import org.apache.cassandra.utils.UUIDGen;
+import org.apache.cassandra.utils.concurrent.Ref;
+
+import static org.apache.cassandra.service.ActiveRepairService.NO_PENDING_REPAIR;
+
+public class CassandraStreamManagerTest
+{
+ private static final String KEYSPACE = null;
+ private String keyspace = null;
+ private static final String table = "tbl";
+ private static final StreamConnectionFactory connectionFactory = new DefaultConnectionFactory();
+
+ private TableMetadata tbm;
+ private ColumnFamilyStore cfs;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ SchemaLoader.prepareServer();
+ }
+
+ @Before
+ public void createKeyspace() throws Exception
+ {
+ keyspace = String.format("ks_%s", System.currentTimeMillis());
+ tbm = CreateTableStatement.parse(String.format("CREATE TABLE %s (k INT PRIMARY KEY, v INT)", table), keyspace).build();
+ SchemaLoader.createKeyspace(keyspace, KeyspaceParams.simple(1), tbm);
+ cfs = Schema.instance.getColumnFamilyStoreInstance(tbm.id);
+ }
+
+ private static StreamSession session(UUID pendingRepair)
+ {
+ try
+ {
+ return new StreamSession(StreamOperation.REPAIR,
+ InetAddressAndPort.getByName("127.0.0.1"),
+ InetAddressAndPort.getByName("127.0.0.2"),
+ connectionFactory,
+ 0,
+ pendingRepair,
+ PreviewKind.NONE);
+ }
+ catch (UnknownHostException e)
+ {
+ throw new AssertionError(e);
+ }
+ }
+
+ private SSTableReader createSSTable(Runnable queryable)
+ {
+ Set<SSTableReader> before = cfs.getLiveSSTables();
+ queryable.run();
+ cfs.forceBlockingFlush();
+ Set<SSTableReader> after = cfs.getLiveSSTables();
+
+ Set<SSTableReader> diff = Sets.difference(after, before);
+ return Iterables.getOnlyElement(diff);
+ }
+
+ private static void mutateRepaired(SSTableReader sstable, long repairedAt, UUID pendingRepair) throws IOException
+ {
+ Descriptor descriptor = sstable.descriptor;
+ descriptor.getMetadataSerializer().mutateRepaired(descriptor, repairedAt, pendingRepair);
+ sstable.reloadSSTableMetadata();
+
+ }
+
+ private static Set<SSTableReader> sstablesFromStreams(Collection<OutgoingStream> streams)
+ {
+ Set<SSTableReader> sstables = new HashSet<>();
+ for (OutgoingStream stream: streams)
+ {
+ Ref<SSTableReader> ref = CassandraOutgoingFile.fromStream(stream).getRef();
+ sstables.add(ref.get());
+ ref.release();
+ }
+ return sstables;
+ }
+
+ private Set<SSTableReader> getReadersForRange(Range<Token> range)
+ {
+ Collection<OutgoingStream> streams = cfs.getStreamManager().createOutgoingStreams(session(NO_PENDING_REPAIR),
+ Collections.singleton(range),
+ NO_PENDING_REPAIR,
+ PreviewKind.NONE);
+ return sstablesFromStreams(streams);
+ }
+
+ private Set<SSTableReader> selectReaders(UUID pendingRepair)
+ {
+ IPartitioner partitioner = DatabaseDescriptor.getPartitioner();
+ Collection<Range<Token>> ranges = Lists.newArrayList(new Range<Token>(partitioner.getMinimumToken(), partitioner.getMinimumToken()));
+ Collection<OutgoingStream> streams = cfs.getStreamManager().createOutgoingStreams(session(pendingRepair), ranges, pendingRepair, PreviewKind.NONE);
+ return sstablesFromStreams(streams);
+ }
+
+ @Test
+ public void incrementalSSTableSelection() throws Exception
+ {
+ // make 3 tables, 1 unrepaired, 2 pending repair with different repair ids, and 1 repaired
+ SSTableReader sstable1 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (1, 1)", keyspace, table)));
+ SSTableReader sstable2 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (2, 2)", keyspace, table)));
+ SSTableReader sstable3 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (3, 3)", keyspace, table)));
+ SSTableReader sstable4 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (4, 4)", keyspace, table)));
+
+
+ UUID pendingRepair = UUIDGen.getTimeUUID();
+ long repairedAt = System.currentTimeMillis();
+ mutateRepaired(sstable2, ActiveRepairService.UNREPAIRED_SSTABLE, pendingRepair);
+ mutateRepaired(sstable3, ActiveRepairService.UNREPAIRED_SSTABLE, UUIDGen.getTimeUUID());
+ mutateRepaired(sstable4, repairedAt, NO_PENDING_REPAIR);
+
+
+
+ // no pending repair should return all sstables
+ Assert.assertEquals(Sets.newHashSet(sstable1, sstable2, sstable3, sstable4), selectReaders(NO_PENDING_REPAIR));
+
+ // a pending repair arg should only return sstables with the same pending repair id
+ Assert.assertEquals(Sets.newHashSet(sstable2), selectReaders(pendingRepair));
+ }
+
+ @Test
+ public void testSSTableSectionsForRanges() throws Exception
+ {
+ cfs.truncateBlocking();
+
+ createSSTable(() -> {
+ QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (1, 1)", keyspace, table));
+ QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (2, 2)", keyspace, table));
+ });
+
+ Collection<SSTableReader> allSSTables = cfs.getLiveSSTables();
+ Assert.assertEquals(1, allSSTables.size());
+ final Token firstToken = allSSTables.iterator().next().first.getToken();
+ DatabaseDescriptor.setSSTablePreempiveOpenIntervalInMB(1);
+
+ Set<SSTableReader> sstablesBeforeRewrite = getReadersForRange(new Range<>(firstToken, firstToken));
+ Assert.assertEquals(1, sstablesBeforeRewrite.size());
+ final AtomicInteger checkCount = new AtomicInteger();
+ // needed since we get notified when compaction is done as well - we can't get sections for ranges for obsoleted sstables
+ final AtomicBoolean done = new AtomicBoolean(false);
+ final AtomicBoolean failed = new AtomicBoolean(false);
+ Runnable r = new Runnable()
+ {
+ public void run()
+ {
+ while (!done.get())
+ {
+ Range<Token> range = new Range<Token>(firstToken, firstToken);
+ Set<SSTableReader> sstables = getReadersForRange(range);
+ if (sstables.size() != 1)
+ failed.set(true);
+ checkCount.incrementAndGet();
+ Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS);
+ }
+ }
+ };
+ Thread t = NamedThreadFactory.createThread(r);
+ try
+ {
+ t.start();
+ cfs.forceMajorCompaction();
+ // reset
+ }
+ finally
+ {
+ DatabaseDescriptor.setSSTablePreempiveOpenIntervalInMB(50);
+ done.set(true);
+ t.join(20);
+ }
+ Assert.assertFalse(failed.get());
+ Assert.assertTrue(checkCount.get() >= 2);
+ cfs.truncateBlocking();
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/dht/StreamStateStoreTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/dht/StreamStateStoreTest.java b/test/unit/org/apache/cassandra/dht/StreamStateStoreTest.java
index ad5f8f5..8f0a407 100644
--- a/test/unit/org/apache/cassandra/dht/StreamStateStoreTest.java
+++ b/test/unit/org/apache/cassandra/dht/StreamStateStoreTest.java
@@ -27,6 +27,7 @@ import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.streaming.DefaultConnectionFactory;
import org.apache.cassandra.streaming.PreviewKind;
import org.apache.cassandra.streaming.StreamEvent;
+import org.apache.cassandra.streaming.StreamOperation;
import org.apache.cassandra.streaming.StreamSession;
import org.apache.cassandra.utils.FBUtilities;
@@ -51,7 +52,7 @@ public class StreamStateStoreTest
Range<Token> range = new Range<>(factory.fromString("0"), factory.fromString("100"));
InetAddressAndPort local = FBUtilities.getBroadcastAddressAndPort();
- StreamSession session = new StreamSession(local, local, new DefaultConnectionFactory(), 0, true, null, PreviewKind.NONE);
+ StreamSession session = new StreamSession(StreamOperation.BOOTSTRAP, local, local, new DefaultConnectionFactory(), 0, null, PreviewKind.NONE);
session.addStreamRequest("keyspace1", Collections.singleton(range), Collections.singleton("cf"));
StreamStateStore store = new StreamStateStore();
@@ -72,7 +73,7 @@ public class StreamStateStoreTest
// add different range within the same keyspace
Range<Token> range2 = new Range<>(factory.fromString("100"), factory.fromString("200"));
- session = new StreamSession(local, local, new DefaultConnectionFactory(), 0, true, null, PreviewKind.NONE);
+ session = new StreamSession(StreamOperation.BOOTSTRAP, local, local, new DefaultConnectionFactory(), 0, null, PreviewKind.NONE);
session.addStreamRequest("keyspace1", Collections.singleton(range2), Collections.singleton("cf"));
session.state(StreamSession.State.COMPLETE);
store.handleStreamEvent(new StreamEvent.SessionCompleteEvent(session));
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java b/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
index e399c67..8dd8197 100644
--- a/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/LegacySSTableTest.java
@@ -26,6 +26,7 @@ import java.util.List;
import java.util.Random;
import java.util.UUID;
+import com.google.common.collect.Lists;
import org.junit.After;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -42,6 +43,7 @@ import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.compaction.Verifier;
+import org.apache.cassandra.db.streaming.CassandraOutgoingFile;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
@@ -52,6 +54,7 @@ import org.apache.cassandra.io.sstable.format.Version;
import org.apache.cassandra.io.sstable.format.big.BigFormat;
import org.apache.cassandra.service.CacheService;
import org.apache.cassandra.service.StorageService;
+import org.apache.cassandra.streaming.OutgoingStream;
import org.apache.cassandra.streaming.StreamPlan;
import org.apache.cassandra.streaming.StreamSession;
import org.apache.cassandra.streaming.StreamOperation;
@@ -248,12 +251,11 @@ public class LegacySSTableTest
List<Range<Token>> ranges = new ArrayList<>();
ranges.add(new Range<>(p.getMinimumToken(), p.getToken(ByteBufferUtil.bytes("100"))));
ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("100")), p.getMinimumToken()));
- ArrayList<StreamSession.SSTableStreamingSections> details = new ArrayList<>();
- details.add(new StreamSession.SSTableStreamingSections(sstable.ref(),
- sstable.getPositionsForRanges(ranges),
- sstable.estimatedKeysForRanges(ranges)));
- new StreamPlan(StreamOperation.OTHER).transferFiles(FBUtilities.getBroadcastAddressAndPort(), details)
- .execute().get();
+ List<OutgoingStream> streams = Lists.newArrayList(new CassandraOutgoingFile(StreamOperation.OTHER,
+ sstable.ref(),
+ sstable.getPositionsForRanges(ranges),
+ sstable.estimatedKeysForRanges(ranges)));
+ new StreamPlan(StreamOperation.OTHER).transferStreams(FBUtilities.getBroadcastAddressAndPort(), streams).execute().get();
}
private static void truncateLegacyTables(String legacyVersion) throws Exception
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java b/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
index 53f5ab3..5c3e8c9 100644
--- a/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
+++ b/test/unit/org/apache/cassandra/io/sstable/SSTableRewriterTest.java
@@ -774,65 +774,6 @@ public class SSTableRewriterTest extends SSTableWriterTestBase
validateCFS(cfs);
}
- @Test
- public void testSSTableSectionsForRanges() throws IOException, InterruptedException, ExecutionException
- {
- Keyspace keyspace = Keyspace.open(KEYSPACE);
- final ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);
- truncate(cfs);
-
- cfs.addSSTable(writeFile(cfs, 1000));
-
- Collection<SSTableReader> allSSTables = cfs.getLiveSSTables();
- assertEquals(1, allSSTables.size());
- final Token firstToken = allSSTables.iterator().next().first.getToken();
- DatabaseDescriptor.setSSTablePreempiveOpenIntervalInMB(1);
-
- List<StreamSession.SSTableStreamingSections> sectionsBeforeRewrite = StreamSession.getSSTableSectionsForRanges(
- Collections.singleton(new Range<Token>(firstToken, firstToken)),
- Collections.singleton(cfs), null, PreviewKind.NONE);
- assertEquals(1, sectionsBeforeRewrite.size());
- for (StreamSession.SSTableStreamingSections section : sectionsBeforeRewrite)
- section.ref.release();
- final AtomicInteger checkCount = new AtomicInteger();
- // needed since we get notified when compaction is done as well - we can't get sections for ranges for obsoleted sstables
- final AtomicBoolean done = new AtomicBoolean(false);
- final AtomicBoolean failed = new AtomicBoolean(false);
- Runnable r = new Runnable()
- {
- public void run()
- {
- while (!done.get())
- {
- Set<Range<Token>> range = Collections.singleton(new Range<Token>(firstToken, firstToken));
- List<StreamSession.SSTableStreamingSections> sections = StreamSession.getSSTableSectionsForRanges(range, Collections.singleton(cfs), null, PreviewKind.NONE);
- if (sections.size() != 1)
- failed.set(true);
- for (StreamSession.SSTableStreamingSections section : sections)
- section.ref.release();
- checkCount.incrementAndGet();
- Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS);
- }
- }
- };
- Thread t = NamedThreadFactory.createThread(r);
- try
- {
- t.start();
- cfs.forceMajorCompaction();
- // reset
- }
- finally
- {
- DatabaseDescriptor.setSSTablePreempiveOpenIntervalInMB(50);
- done.set(true);
- t.join(20);
- }
- assertFalse(failed.get());
- assertTrue(checkCount.get() >= 2);
- truncate(cfs);
- }
-
/**
* emulates anticompaction - writing from one source sstable to two new sstables
*
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/serializers/SerializationUtils.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/serializers/SerializationUtils.java b/test/unit/org/apache/cassandra/serializers/SerializationUtils.java
new file mode 100644
index 0000000..7ce4ec5
--- /dev/null
+++ b/test/unit/org/apache/cassandra/serializers/SerializationUtils.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.serializers;
+
+import java.io.IOException;
+
+import org.junit.Assert;
+
+import org.apache.cassandra.io.IVersionedSerializer;
+import org.apache.cassandra.io.util.DataInputBuffer;
+import org.apache.cassandra.io.util.DataOutputBuffer;
+import org.apache.cassandra.net.MessagingService;
+
+public class SerializationUtils
+{
+
+ public static <T> T cycleSerialization(T src, IVersionedSerializer<T> serializer, int version)
+ {
+ int expectedSize = (int) serializer.serializedSize(src, version);
+
+ try (DataOutputBuffer out = new DataOutputBuffer(expectedSize))
+ {
+ serializer.serialize(src, out, version);
+ Assert.assertEquals(expectedSize, out.buffer().limit());
+ try (DataInputBuffer in = new DataInputBuffer(out.buffer(), false))
+ {
+ return serializer.deserialize(in, version);
+ }
+ }
+ catch (IOException e)
+ {
+ throw new AssertionError(e);
+ }
+ }
+
+ public static <T> T cycleSerialization(T src, IVersionedSerializer<T> serializer)
+ {
+ return cycleSerialization(src, serializer, MessagingService.current_version);
+ }
+
+ public static <T> void assertSerializationCycle(T src, IVersionedSerializer<T> serializer, int version)
+ {
+ T dst = cycleSerialization(src, serializer, version);
+ Assert.assertEquals(src, dst);
+ }
+
+ public static <T> void assertSerializationCycle(T src, IVersionedSerializer<T> serializer)
+ {
+ assertSerializationCycle(src, serializer, MessagingService.current_version);
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/streaming/StreamSessionTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/StreamSessionTest.java b/test/unit/org/apache/cassandra/streaming/StreamSessionTest.java
deleted file mode 100644
index 6abc2a2..0000000
--- a/test/unit/org/apache/cassandra/streaming/StreamSessionTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.cassandra.streaming;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import org.apache.cassandra.SchemaLoader;
-import org.apache.cassandra.config.DatabaseDescriptor;
-import org.apache.cassandra.cql3.QueryProcessor;
-import org.apache.cassandra.cql3.statements.CreateTableStatement;
-import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.dht.IPartitioner;
-import org.apache.cassandra.dht.Range;
-import org.apache.cassandra.dht.Token;
-import org.apache.cassandra.io.sstable.Descriptor;
-import org.apache.cassandra.io.sstable.format.SSTableReader;
-import org.apache.cassandra.schema.KeyspaceParams;
-import org.apache.cassandra.schema.Schema;
-import org.apache.cassandra.schema.TableMetadata;
-import org.apache.cassandra.service.ActiveRepairService;
-import org.apache.cassandra.utils.UUIDGen;
-
-public class StreamSessionTest
-{
- private String keyspace = null;
- private static final String table = "tbl";
-
- private TableMetadata tbm;
- private ColumnFamilyStore cfs;
-
- @BeforeClass
- public static void setupClass() throws Exception
- {
- SchemaLoader.prepareServer();
- }
-
- @Before
- public void createKeyspace() throws Exception
- {
- keyspace = String.format("ks_%s", System.currentTimeMillis());
- tbm = CreateTableStatement.parse(String.format("CREATE TABLE %s (k INT PRIMARY KEY, v INT)", table), keyspace).build();
- SchemaLoader.createKeyspace(keyspace, KeyspaceParams.simple(1), tbm);
- cfs = Schema.instance.getColumnFamilyStoreInstance(tbm.id);
- }
-
- private SSTableReader createSSTable(Runnable queryable)
- {
- Set<SSTableReader> before = cfs.getLiveSSTables();
- queryable.run();
- cfs.forceBlockingFlush();
- Set<SSTableReader> after = cfs.getLiveSSTables();
-
- Set<SSTableReader> diff = Sets.difference(after, before);
- assert diff.size() == 1 : "Expected 1 new sstable, got " + diff.size();
- return diff.iterator().next();
- }
-
- private static void mutateRepaired(SSTableReader sstable, long repairedAt, UUID pendingRepair) throws IOException
- {
- Descriptor descriptor = sstable.descriptor;
- descriptor.getMetadataSerializer().mutateRepaired(descriptor, repairedAt, pendingRepair);
- sstable.reloadSSTableMetadata();
-
- }
-
- private Set<SSTableReader> selectReaders(UUID pendingRepair)
- {
- IPartitioner partitioner = DatabaseDescriptor.getPartitioner();
- Collection<Range<Token>> ranges = Lists.newArrayList(new Range<Token>(partitioner.getMinimumToken(), partitioner.getMinimumToken()));
- List<StreamSession.SSTableStreamingSections> sections = StreamSession.getSSTableSectionsForRanges(ranges,
- Lists.newArrayList(cfs),
- pendingRepair,
- PreviewKind.NONE);
- Set<SSTableReader> sstables = new HashSet<>();
- for (StreamSession.SSTableStreamingSections section: sections)
- {
- sstables.add(section.ref.get());
- }
- return sstables;
- }
-
- @Test
- public void incrementalSSTableSelection() throws Exception
- {
- // make 3 tables, 1 unrepaired, 2 pending repair with different repair ids, and 1 repaired
- SSTableReader sstable1 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (1, 1)", keyspace, table)));
- SSTableReader sstable2 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (2, 2)", keyspace, table)));
- SSTableReader sstable3 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (3, 3)", keyspace, table)));
- SSTableReader sstable4 = createSSTable(() -> QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (k, v) VALUES (4, 4)", keyspace, table)));
-
-
- UUID pendingRepair = UUIDGen.getTimeUUID();
- long repairedAt = System.currentTimeMillis();
- mutateRepaired(sstable2, ActiveRepairService.UNREPAIRED_SSTABLE, pendingRepair);
- mutateRepaired(sstable3, ActiveRepairService.UNREPAIRED_SSTABLE, UUIDGen.getTimeUUID());
- mutateRepaired(sstable4, repairedAt, ActiveRepairService.NO_PENDING_REPAIR);
-
- // no pending repair should return all sstables
- Assert.assertEquals(Sets.newHashSet(sstable1, sstable2, sstable3, sstable4), selectReaders(ActiveRepairService.NO_PENDING_REPAIR));
-
- // a pending repair arg should only return sstables with the same pending repair id
- Assert.assertEquals(Sets.newHashSet(sstable2), selectReaders(pendingRepair));
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java b/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
index ceaaae0..45c917a 100644
--- a/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
+++ b/test/unit/org/apache/cassandra/streaming/StreamTransferTaskTest.java
@@ -36,6 +36,7 @@ import junit.framework.Assert;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
+import org.apache.cassandra.db.streaming.CassandraOutgoingFile;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.ConfigurationException;
@@ -43,7 +44,7 @@ import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.schema.TableId;
-import org.apache.cassandra.streaming.messages.OutgoingFileMessage;
+import org.apache.cassandra.streaming.messages.OutgoingStreamMessage;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.concurrent.Ref;
@@ -75,7 +76,7 @@ public class StreamTransferTaskTest
public void testScheduleTimeout() throws Exception
{
InetAddressAndPort peer = FBUtilities.getBroadcastAddressAndPort();
- StreamSession session = new StreamSession(peer, peer, (connectionId, protocolVersion) -> new EmbeddedChannel(), 0, true, UUID.randomUUID(), PreviewKind.ALL);
+ StreamSession session = new StreamSession(StreamOperation.BOOTSTRAP, peer, peer, (connectionId, protocolVersion) -> new EmbeddedChannel(), 0, UUID.randomUUID(), PreviewKind.ALL);
ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD);
// create two sstables
@@ -91,7 +92,7 @@ public class StreamTransferTaskTest
{
List<Range<Token>> ranges = new ArrayList<>();
ranges.add(new Range<>(sstable.first.getToken(), sstable.last.getToken()));
- task.addTransferFile(sstable.selfRef(), 1, sstable.getPositionsForRanges(ranges));
+ task.addTransferStream(new CassandraOutgoingFile(StreamOperation.BOOTSTRAP, sstable.selfRef(), sstable.getPositionsForRanges(ranges), 1));
}
assertEquals(2, task.getTotalNumberOfFiles());
@@ -121,9 +122,9 @@ public class StreamTransferTaskTest
public void testFailSessionDuringTransferShouldNotReleaseReferences() throws Exception
{
InetAddressAndPort peer = FBUtilities.getBroadcastAddressAndPort();
- StreamCoordinator streamCoordinator = new StreamCoordinator(1, true, new DefaultConnectionFactory(), false, null, PreviewKind.NONE);
+ StreamCoordinator streamCoordinator = new StreamCoordinator(StreamOperation.BOOTSTRAP, 1, new DefaultConnectionFactory(), false, null, PreviewKind.NONE);
StreamResultFuture future = StreamResultFuture.init(UUID.randomUUID(), StreamOperation.OTHER, Collections.<StreamEventHandler>emptyList(), streamCoordinator);
- StreamSession session = new StreamSession(peer, peer, null, 0, true, null, PreviewKind.NONE);
+ StreamSession session = new StreamSession(StreamOperation.BOOTSTRAP, peer, peer, null, 0, null, PreviewKind.NONE);
session.init(future);
ColumnFamilyStore cfs = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD);
@@ -143,7 +144,7 @@ public class StreamTransferTaskTest
ranges.add(new Range<>(sstable.first.getToken(), sstable.last.getToken()));
Ref<SSTableReader> ref = sstable.selfRef();
refs.add(ref);
- task.addTransferFile(ref, 1, sstable.getPositionsForRanges(ranges));
+ task.addTransferStream(new CassandraOutgoingFile(StreamOperation.BOOTSTRAP, ref, sstable.getPositionsForRanges(ranges), 1));
}
assertEquals(2, task.getTotalNumberOfFiles());
@@ -151,10 +152,10 @@ public class StreamTransferTaskTest
session.transfers.put(TableId.generate(), task);
//make a copy of outgoing file messages, since task is cleared when it's aborted
- Collection<OutgoingFileMessage> files = new LinkedList<>(task.files.values());
+ Collection<OutgoingStreamMessage> files = new LinkedList<>(task.streams.values());
//simulate start transfer
- for (OutgoingFileMessage file : files)
+ for (OutgoingStreamMessage file : files)
{
file.startTransfer();
}
@@ -169,7 +170,7 @@ public class StreamTransferTaskTest
}
//simulate finish transfer
- for (OutgoingFileMessage file : files)
+ for (OutgoingStreamMessage file : files)
{
file.finishTransfer();
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/streaming/StreamingTransferTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/StreamingTransferTest.java b/test/unit/org/apache/cassandra/streaming/StreamingTransferTest.java
index 16c07a0..575200a 100644
--- a/test/unit/org/apache/cassandra/streaming/StreamingTransferTest.java
+++ b/test/unit/org/apache/cassandra/streaming/StreamingTransferTest.java
@@ -34,6 +34,7 @@ import junit.framework.Assert;
import org.apache.cassandra.OrderedJUnit4ClassRunner;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.Util;
+import org.apache.cassandra.db.streaming.CassandraOutgoingFile;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.config.DatabaseDescriptor;
@@ -254,13 +255,13 @@ public class StreamingTransferTest
private void transfer(SSTableReader sstable, List<Range<Token>> ranges) throws Exception
{
- StreamPlan streamPlan = new StreamPlan(StreamOperation.OTHER).transferFiles(LOCAL, makeStreamingDetails(ranges, Refs.tryRef(Arrays.asList(sstable))));
+ StreamPlan streamPlan = new StreamPlan(StreamOperation.OTHER).transferStreams(LOCAL, makeOutgoingStreams(ranges, Refs.tryRef(Arrays.asList(sstable))));
streamPlan.execute().get();
//cannot add files after stream session is finished
try
{
- streamPlan.transferFiles(LOCAL, makeStreamingDetails(ranges, Refs.tryRef(Arrays.asList(sstable))));
+ streamPlan.transferStreams(LOCAL, makeOutgoingStreams(ranges, Refs.tryRef(Arrays.asList(sstable))));
fail("Should have thrown exception");
}
catch (RuntimeException e)
@@ -269,16 +270,22 @@ public class StreamingTransferTest
}
}
- private Collection<StreamSession.SSTableStreamingSections> makeStreamingDetails(List<Range<Token>> ranges, Refs<SSTableReader> sstables)
+ private Collection<OutgoingStream> makeOutgoingStreams(StreamOperation operation, List<Range<Token>> ranges, Refs<SSTableReader> sstables)
{
- ArrayList<StreamSession.SSTableStreamingSections> details = new ArrayList<>();
+ ArrayList<OutgoingStream> streams = new ArrayList<>();
for (SSTableReader sstable : sstables)
{
- details.add(new StreamSession.SSTableStreamingSections(sstables.get(sstable),
- sstable.getPositionsForRanges(ranges),
- sstable.estimatedKeysForRanges(ranges)));
+ streams.add(new CassandraOutgoingFile(operation,
+ sstables.get(sstable),
+ sstable.getPositionsForRanges(ranges),
+ sstable.estimatedKeysForRanges(ranges)));
}
- return details;
+ return streams;
+ }
+
+ private Collection<OutgoingStream> makeOutgoingStreams(List<Range<Token>> ranges, Refs<SSTableReader> sstables)
+ {
+ return makeOutgoingStreams(StreamOperation.OTHER, ranges, sstables);
}
private void doTransferTable(boolean transferSSTables) throws Exception
@@ -458,7 +465,7 @@ public class StreamingTransferTest
// Acquiring references, transferSSTables needs it
Refs<SSTableReader> refs = Refs.tryRef(Arrays.asList(sstable, sstable2));
assert refs != null;
- new StreamPlan("StreamingTransferTest").transferFiles(LOCAL, makeStreamingDetails(ranges, refs)).execute().get();
+ new StreamPlan("StreamingTransferTest").transferStreams(LOCAL, makeOutgoingStreams(ranges, refs)).execute().get();
// confirm that the sstables were transferred and registered and that 2 keys arrived
ColumnFamilyStore cfstore = Keyspace.open(keyspaceName).getColumnFamilyStore(cfname);
@@ -513,7 +520,7 @@ public class StreamingTransferTest
if (refs == null)
throw new AssertionError();
- new StreamPlan("StreamingTransferTest").transferFiles(LOCAL, makeStreamingDetails(ranges, refs)).execute().get();
+ new StreamPlan("StreamingTransferTest").transferStreams(LOCAL, makeOutgoingStreams(ranges, refs)).execute().get();
// check that only two keys were transferred
for (Map.Entry<DecoratedKey,String> entry : Arrays.asList(first, last))
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/test/unit/org/apache/cassandra/streaming/async/NettyStreamingMessageSenderTest.java
----------------------------------------------------------------------
diff --git a/test/unit/org/apache/cassandra/streaming/async/NettyStreamingMessageSenderTest.java b/test/unit/org/apache/cassandra/streaming/async/NettyStreamingMessageSenderTest.java
index 617bae1..fd22a65 100644
--- a/test/unit/org/apache/cassandra/streaming/async/NettyStreamingMessageSenderTest.java
+++ b/test/unit/org/apache/cassandra/streaming/async/NettyStreamingMessageSenderTest.java
@@ -18,7 +18,6 @@
package org.apache.cassandra.streaming.async;
-import java.net.InetSocketAddress;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@@ -64,8 +63,8 @@ public class NettyStreamingMessageSenderTest
channel = new EmbeddedChannel();
channel.attr(NettyStreamingMessageSender.TRANSFERRING_FILE_ATTR).set(Boolean.FALSE);
UUID pendingRepair = UUID.randomUUID();
- session = new StreamSession(REMOTE_ADDR, REMOTE_ADDR, (connectionId, protocolVersion) -> null, 0, true, pendingRepair, PreviewKind.ALL);
- StreamResultFuture future = StreamResultFuture.initReceivingSide(0, UUID.randomUUID(), StreamOperation.REPAIR, REMOTE_ADDR, channel, true, pendingRepair, session.getPreviewKind());
+ session = new StreamSession(StreamOperation.BOOTSTRAP, REMOTE_ADDR, REMOTE_ADDR, (connectionId, protocolVersion) -> null, 0, pendingRepair, PreviewKind.ALL);
+ StreamResultFuture future = StreamResultFuture.initReceivingSide(0, UUID.randomUUID(), StreamOperation.REPAIR, REMOTE_ADDR, channel, pendingRepair, session.getPreviewKind());
session.init(future);
sender = session.getMessageSender();
sender.setControlMessageChannel(channel);
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
[3/5] cassandra git commit: Abstract streaming for pluggable storage
Posted by bd...@apache.org.
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamSession.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamSession.java b/src/java/org/apache/cassandra/streaming/StreamSession.java
index 4085c43..adf5d76 100644
--- a/src/java/org/apache/cassandra/streaming/StreamSession.java
+++ b/src/java/org/apache/cassandra/streaming/StreamSession.java
@@ -17,27 +17,17 @@
*/
package org.apache.cassandra.streaming;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
import com.google.common.collect.*;
import com.google.common.util.concurrent.Futures;
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.config.DatabaseDescriptor;
-import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
-import org.apache.cassandra.db.lifecycle.SSTableIntervalTree;
-import org.apache.cassandra.db.lifecycle.SSTableSet;
-import org.apache.cassandra.db.lifecycle.View;
-import org.apache.cassandra.io.sstable.SSTableMultiWriter;
-import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,7 +35,6 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
-import org.apache.cassandra.db.PartitionPosition;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.gms.*;
@@ -54,19 +43,13 @@ import org.apache.cassandra.metrics.StreamingMetrics;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.net.async.OutboundConnectionIdentifier;
import org.apache.cassandra.schema.TableId;
-import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.streaming.async.NettyStreamingMessageSender;
import org.apache.cassandra.streaming.messages.*;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.JVMStabilityInspector;
-import org.apache.cassandra.utils.Pair;
-import org.apache.cassandra.utils.concurrent.Ref;
-import org.apache.cassandra.utils.concurrent.Refs;
/**
- * Handles the streaming a one or more section of one of more sstables to and from a specific
- * remote node. The sending side performs a block-level transfer of the source sstable, while the receiver
- * must deserilaize that data stream into an partitions and rows, and then write that out as an sstable.
+ * Handles the streaming a one or more streams to and from a specific remote node.
*
* Both this node and the remote one will create a similar symmetrical {@link StreamSession}. A streaming
* session has the following life-cycle:
@@ -98,15 +81,15 @@ import org.apache.cassandra.utils.concurrent.Refs;
*
* (a) The streaming phase is started at each node by calling {@link StreamSession#startStreamingFiles(boolean)}.
* This will send, sequentially on each outbound streaming connection (see {@link NettyStreamingMessageSender}),
- * an {@link OutgoingFileMessage} for each file in each of the {@link StreamTransferTask}.
- * Each {@link OutgoingFileMessage} consists of a {@link FileMessageHeader} that contains metadata about the file
- * being streamed, followed by the file content itself. Once all the files for a {@link StreamTransferTask} are sent,
+ * an {@link OutgoingStreamMessage} for each stream in each of the {@link StreamTransferTask}.
+ * Each {@link OutgoingStreamMessage} consists of a {@link StreamMessageHeader} that contains metadata about
+ * the stream, followed by the stream content itself. Once all the files for a {@link StreamTransferTask} are sent,
* the task is marked complete {@link StreamTransferTask#complete(int)}.
- * (b) On the receiving side, a SSTable will be written for the incoming file, and once the file is fully received,
- * the file will be marked as complete ({@link StreamReceiveTask#received(SSTableMultiWriter)}). When all files
- * for the {@link StreamReceiveTask} have been received, the sstables are added to the CFS (and 2ndary indexes/MV are built),
+ * (b) On the receiving side, the incoming data is written to disk, and once the stream is fully received,
+ * it will be marked as complete ({@link StreamReceiveTask#received(IncomingStream)}). When all streams
+ * for the {@link StreamReceiveTask} have been received, the data is added to the CFS (and 2ndary indexes/MV are built),
* and the task is marked complete ({@link #taskCompleted(StreamReceiveTask)}).
- * (b) If during the streaming of a particular file an error occurs on the receiving end of a stream
+ * (b) If during the streaming of a particular stream an error occurs on the receiving end of a stream
* (it may be either the initiator or the follower), the node will send a {@link SessionFailedMessage}
* to the sender and close the stream session.
* (c) When all transfer and receive tasks for a session are complete, the session moves to the Completion phase
@@ -127,7 +110,7 @@ import org.apache.cassandra.utils.concurrent.Refs;
* F: PrepareSynAckMessage
* I: PrepareAckMessage
* (stream - this can happen in both directions)
- * I: OutgoingFileMessage
+ * I: OutgoingStreamMessage
* F: ReceivedMessage
* (completion)
* I/F: CompleteMessage
@@ -140,6 +123,7 @@ public class StreamSession implements IEndpointStateChangeSubscriber
{
private static final Logger logger = LoggerFactory.getLogger(StreamSession.class);
+ private final StreamOperation streamOperation;
/**
* Streaming endpoint.
*
@@ -170,7 +154,6 @@ public class StreamSession implements IEndpointStateChangeSubscriber
private final ConcurrentMap<ChannelId, Channel> incomingChannels = new ConcurrentHashMap<>();
private final AtomicBoolean isAborted = new AtomicBoolean(false);
- private final boolean keepSSTableLevel;
private final UUID pendingRepair;
private final PreviewKind previewKind;
@@ -189,11 +172,13 @@ public class StreamSession implements IEndpointStateChangeSubscriber
/**
* Create new streaming session with the peer.
- * @param peer Address of streaming peer
+ * @param streamOperation
+ * @param peer Address of streaming peer
* @param connecting Actual connecting address
*/
- public StreamSession(InetAddressAndPort peer, InetAddressAndPort connecting, StreamConnectionFactory factory, int index, boolean keepSSTableLevel, UUID pendingRepair, PreviewKind previewKind)
+ public StreamSession(StreamOperation streamOperation, InetAddressAndPort peer, InetAddressAndPort connecting, StreamConnectionFactory factory, int index, UUID pendingRepair, PreviewKind previewKind)
{
+ this.streamOperation = streamOperation;
this.peer = peer;
this.connecting = connecting;
this.index = index;
@@ -202,7 +187,6 @@ public class StreamSession implements IEndpointStateChangeSubscriber
InetAddressAndPort.getByAddressOverrideDefaults(connecting.address, MessagingService.instance().portFor(connecting)));
this.messageSender = new NettyStreamingMessageSender(this, id, factory, StreamMessage.CURRENT_VERSION, previewKind.isPreview());
this.metrics = StreamingMetrics.get(connecting);
- this.keepSSTableLevel = keepSSTableLevel;
this.pendingRepair = pendingRepair;
this.previewKind = previewKind;
}
@@ -222,9 +206,9 @@ public class StreamSession implements IEndpointStateChangeSubscriber
return streamResult == null ? null : streamResult.streamOperation;
}
- public boolean keepSSTableLevel()
+ public StreamOperation getStreamOperation()
{
- return keepSSTableLevel;
+ return streamOperation;
}
public UUID getPendingRepair()
@@ -242,10 +226,10 @@ public class StreamSession implements IEndpointStateChangeSubscriber
return previewKind;
}
- public LifecycleTransaction getTransaction(TableId tableId)
+ public StreamReceiver getAggregator(TableId tableId)
{
assert receivers.containsKey(tableId);
- return receivers.get(tableId).getTransaction();
+ return receivers.get(tableId).getReceiver();
}
/**
@@ -309,8 +293,6 @@ public class StreamSession implements IEndpointStateChangeSubscriber
/**
* Set up transfer for specific keyspace/ranges/CFs
*
- * Used in repair - a streamed sstable in repair will be marked with the given repairedAt time
- *
* @param keyspace Transfer keyspace
* @param ranges Transfer ranges
* @param columnFamilies Transfer ColumnFamilies
@@ -324,23 +306,15 @@ public class StreamSession implements IEndpointStateChangeSubscriber
flushSSTables(stores);
List<Range<Token>> normalizedRanges = Range.normalize(ranges);
- List<SSTableStreamingSections> sections = getSSTableSectionsForRanges(normalizedRanges, stores, pendingRepair, previewKind);
- try
- {
- addTransferFiles(sections);
- Set<Range<Token>> toBeUpdated = transferredRangesPerKeyspace.get(keyspace);
- if (toBeUpdated == null)
- {
- toBeUpdated = new HashSet<>();
- }
- toBeUpdated.addAll(ranges);
- transferredRangesPerKeyspace.put(keyspace, toBeUpdated);
- }
- finally
+ List<OutgoingStream> streams = getOutgoingStreamsForRanges(normalizedRanges, stores, pendingRepair, previewKind);
+ addTransferStreams(streams);
+ Set<Range<Token>> toBeUpdated = transferredRangesPerKeyspace.get(keyspace);
+ if (toBeUpdated == null)
{
- for (SSTableStreamingSections release : sections)
- release.ref.release();
+ toBeUpdated = new HashSet<>();
}
+ toBeUpdated.addAll(ranges);
+ transferredRangesPerKeyspace.put(keyspace, toBeUpdated);
}
private void failIfFinished()
@@ -366,83 +340,30 @@ public class StreamSession implements IEndpointStateChangeSubscriber
}
@VisibleForTesting
- public static List<SSTableStreamingSections> getSSTableSectionsForRanges(Collection<Range<Token>> ranges, Collection<ColumnFamilyStore> stores, UUID pendingRepair, PreviewKind previewKind)
+ public List<OutgoingStream> getOutgoingStreamsForRanges(Collection<Range<Token>> ranges, Collection<ColumnFamilyStore> stores, UUID pendingRepair, PreviewKind previewKind)
{
- Refs<SSTableReader> refs = new Refs<>();
+ List<OutgoingStream> streams = new ArrayList<>();
try
{
- for (ColumnFamilyStore cfStore : stores)
- {
- final List<Range<PartitionPosition>> keyRanges = new ArrayList<>(ranges.size());
- for (Range<Token> range : ranges)
- keyRanges.add(Range.makeRowRange(range));
- refs.addAll(cfStore.selectAndReference(view -> {
- Set<SSTableReader> sstables = Sets.newHashSet();
- SSTableIntervalTree intervalTree = SSTableIntervalTree.build(view.select(SSTableSet.CANONICAL));
- Predicate<SSTableReader> predicate;
- if (previewKind.isPreview())
- {
- predicate = previewKind.getStreamingPredicate();
- }
- else if (pendingRepair == ActiveRepairService.NO_PENDING_REPAIR)
- {
- predicate = Predicates.alwaysTrue();
- }
- else
- {
- predicate = s -> s.isPendingRepair() && s.getSSTableMetadata().pendingRepair.equals(pendingRepair);
- }
-
- for (Range<PartitionPosition> keyRange : keyRanges)
- {
- // keyRange excludes its start, while sstableInBounds is inclusive (of both start and end).
- // This is fine however, because keyRange has been created from a token range through Range.makeRowRange (see above).
- // And that later method uses the Token.maxKeyBound() method to creates the range, which return a "fake" key that
- // sort after all keys having the token. That "fake" key cannot however be equal to any real key, so that even
- // including keyRange.left will still exclude any key having the token of the original token range, and so we're
- // still actually selecting what we wanted.
- for (SSTableReader sstable : Iterables.filter(View.sstablesInBounds(keyRange.left, keyRange.right, intervalTree), predicate))
- {
- sstables.add(sstable);
- }
- }
-
- if (logger.isDebugEnabled())
- logger.debug("ViewFilter for {}/{} sstables", sstables.size(), Iterables.size(view.select(SSTableSet.CANONICAL)));
- return sstables;
- }).refs);
- }
-
- List<SSTableStreamingSections> sections = new ArrayList<>(refs.size());
- for (SSTableReader sstable : refs)
+ for (ColumnFamilyStore cfs: stores)
{
- sections.add(new SSTableStreamingSections(refs.get(sstable), sstable.getPositionsForRanges(ranges), sstable.estimatedKeysForRanges(ranges)));
+ streams.addAll(cfs.getStreamManager().createOutgoingStreams(this, ranges, pendingRepair, previewKind));
}
- return sections;
}
catch (Throwable t)
{
- refs.release();
+ streams.forEach(OutgoingStream::finish);
throw t;
}
+ return streams;
}
- synchronized void addTransferFiles(Collection<SSTableStreamingSections> sstableDetails)
+ synchronized void addTransferStreams(Collection<OutgoingStream> streams)
{
failIfFinished();
- Iterator<SSTableStreamingSections> iter = sstableDetails.iterator();
- while (iter.hasNext())
+ for (OutgoingStream stream: streams)
{
- SSTableStreamingSections details = iter.next();
- if (details.sections.isEmpty())
- {
- // A reference was acquired on the sstable and we won't stream it
- details.ref.release();
- iter.remove();
- continue;
- }
-
- TableId tableId = details.ref.get().metadata().id;
+ TableId tableId = stream.getTableId();
StreamTransferTask task = transfers.get(tableId);
if (task == null)
{
@@ -452,22 +373,7 @@ public class StreamSession implements IEndpointStateChangeSubscriber
if (task == null)
task = newTask;
}
- task.addTransferFile(details.ref, details.estimatedKeys, details.sections);
- iter.remove();
- }
- }
-
- public static class SSTableStreamingSections
- {
- public final Ref<SSTableReader> ref;
- public final List<Pair<Long, Long>> sections;
- public final long estimatedKeys;
-
- public SSTableStreamingSections(Ref<SSTableReader> ref, List<Pair<Long, Long>> sections, long estimatedKeys)
- {
- this.ref = ref;
- this.sections = sections;
- this.estimatedKeys = estimatedKeys;
+ task.addTransferStream(stream);
}
}
@@ -554,8 +460,8 @@ public class StreamSession implements IEndpointStateChangeSubscriber
case PREPARE_ACK:
prepareAck((PrepareAckMessage) message);
break;
- case FILE:
- receive((IncomingFileMessage) message);
+ case STREAM:
+ receive((IncomingStreamMessage) message);
break;
case RECEIVED:
ReceivedMessage received = (ReceivedMessage) message;
@@ -681,41 +587,42 @@ public class StreamSession implements IEndpointStateChangeSubscriber
}
/**
- * Call back after sending FileMessageHeader.
+ * Call back after sending StreamMessageHeader.
*
- * @param header sent header
+ * @param message sent stream message
*/
- public void fileSent(FileMessageHeader header)
+ public void streamSent(OutgoingStreamMessage message)
{
- long headerSize = header.size();
+ long headerSize = message.stream.getSize();
StreamingMetrics.totalOutgoingBytes.inc(headerSize);
metrics.outgoingBytes.inc(headerSize);
// schedule timeout for receiving ACK
- StreamTransferTask task = transfers.get(header.tableId);
+ StreamTransferTask task = transfers.get(message.header.tableId);
if (task != null)
{
- task.scheduleTimeout(header.sequenceNumber, 12, TimeUnit.HOURS);
+ task.scheduleTimeout(message.header.sequenceNumber, 12, TimeUnit.HOURS);
}
}
/**
- * Call back after receiving a streamed file.
+ * Call back after receiving a stream.
*
- * @param message received file
+ * @param message received stream
*/
- public void receive(IncomingFileMessage message)
+ public void receive(IncomingStreamMessage message)
{
if (isPreview())
{
throw new RuntimeException("Cannot receive files for preview session");
}
- long headerSize = message.header.size();
+ long headerSize = message.stream.getSize();
StreamingMetrics.totalIncomingBytes.inc(headerSize);
metrics.incomingBytes.inc(headerSize);
// send back file received message
messageSender.sendMessage(new ReceivedMessage(message.header.tableId, message.header.sequenceNumber));
- receivers.get(message.header.tableId).received(message.sstable);
+ StreamHook.instance.reportIncomingStream(message.header.tableId, message.stream, this, message.header.sequenceNumber);
+ receivers.get(message.header.tableId).received(message.stream);
}
public void progress(String filename, ProgressInfo.Direction direction, long bytes, long total)
@@ -812,8 +719,8 @@ public class StreamSession implements IEndpointStateChangeSubscriber
}
finally
{
- // aborting the tasks here needs to be the last thing we do so that we
- // accurately report expected streaming, but don't leak any sstable refs
+ // aborting the tasks here needs to be the last thing we do so that we accurately report
+ // expected streaming, but don't leak any resources held by the task
for (StreamTask task : Iterables.concat(receivers.values(), transfers.values()))
task.abort();
}
@@ -872,10 +779,10 @@ public class StreamSession implements IEndpointStateChangeSubscriber
for (StreamTransferTask task : transfers.values())
{
- Collection<OutgoingFileMessage> messages = task.getFileMessages();
+ Collection<OutgoingStreamMessage> messages = task.getFileMessages();
if (!messages.isEmpty())
{
- for (OutgoingFileMessage ofm : messages)
+ for (OutgoingStreamMessage ofm : messages)
{
// pass the session planId/index to the OFM (which is only set at init(), after the transfers have already been created)
ofm.header.addSessionInfo(this);
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamTransferTask.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamTransferTask.java b/src/java/org/apache/cassandra/streaming/StreamTransferTask.java
index 5e21712..802188a 100644
--- a/src/java/org/apache/cassandra/streaming/StreamTransferTask.java
+++ b/src/java/org/apache/cassandra/streaming/StreamTransferTask.java
@@ -24,20 +24,18 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.NamedThreadFactory;
-import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.TableId;
-import org.apache.cassandra.streaming.messages.OutgoingFileMessage;
-import org.apache.cassandra.utils.Pair;
-import org.apache.cassandra.utils.concurrent.Ref;
+import org.apache.cassandra.streaming.messages.OutgoingStreamMessage;
/**
- * StreamTransferTask sends sections of SSTable files in certain ColumnFamily.
+ * StreamTransferTask sends streams for a given table
*/
public class StreamTransferTask extends StreamTask
{
@@ -48,7 +46,7 @@ public class StreamTransferTask extends StreamTask
private boolean aborted = false;
@VisibleForTesting
- protected final Map<Integer, OutgoingFileMessage> files = new HashMap<>();
+ protected final Map<Integer, OutgoingStreamMessage> streams = new HashMap<>();
private final Map<Integer, ScheduledFuture> timeoutTasks = new HashMap<>();
private long totalSize;
@@ -58,19 +56,19 @@ public class StreamTransferTask extends StreamTask
super(session, tableId);
}
- public synchronized void addTransferFile(Ref<SSTableReader> ref, long estimatedKeys, List<Pair<Long, Long>> sections)
+ public synchronized void addTransferStream(OutgoingStream stream)
{
- assert ref.get() != null && tableId.equals(ref.get().metadata().id);
- OutgoingFileMessage message = new OutgoingFileMessage(ref, session, sequenceNumber.getAndIncrement(), estimatedKeys, sections, session.keepSSTableLevel());
- message = StreamHook.instance.reportOutgoingFile(session, ref.get(), message);
- files.put(message.header.sequenceNumber, message);
- totalSize += message.header.size();
+ Preconditions.checkArgument(tableId.equals(stream.getTableId()));
+ OutgoingStreamMessage message = new OutgoingStreamMessage(tableId, session, stream, sequenceNumber.getAndIncrement());
+ message = StreamHook.instance.reportOutgoingStream(session, stream, message);
+ streams.put(message.header.sequenceNumber, message);
+ totalSize += message.stream.getSize();
}
/**
- * Received ACK for file at {@code sequenceNumber}.
+ * Received ACK for stream at {@code sequenceNumber}.
*
- * @param sequenceNumber sequence number of file
+ * @param sequenceNumber sequence number of stream
*/
public void complete(int sequenceNumber)
{
@@ -81,12 +79,12 @@ public class StreamTransferTask extends StreamTask
if (timeout != null)
timeout.cancel(false);
- OutgoingFileMessage file = files.remove(sequenceNumber);
- if (file != null)
- file.complete();
+ OutgoingStreamMessage stream = streams.remove(sequenceNumber);
+ if (stream != null)
+ stream.complete();
- logger.debug("recevied sequenceNumber {}, remaining files {}", sequenceNumber, files.keySet());
- signalComplete = files.isEmpty();
+ logger.debug("recevied sequenceNumber {}, remaining files {}", sequenceNumber, streams.keySet());
+ signalComplete = streams.isEmpty();
}
// all file sent, notify session this task is complete.
@@ -105,11 +103,11 @@ public class StreamTransferTask extends StreamTask
timeoutTasks.clear();
Throwable fail = null;
- for (OutgoingFileMessage file : files.values())
+ for (OutgoingStreamMessage stream : streams.values())
{
try
{
- file.complete();
+ stream.complete();
}
catch (Throwable t)
{
@@ -117,14 +115,14 @@ public class StreamTransferTask extends StreamTask
else fail.addSuppressed(t);
}
}
- files.clear();
+ streams.clear();
if (fail != null)
Throwables.propagate(fail);
}
public synchronized int getTotalNumberOfFiles()
{
- return files.size();
+ return streams.size();
}
public long getTotalSize()
@@ -132,35 +130,35 @@ public class StreamTransferTask extends StreamTask
return totalSize;
}
- public synchronized Collection<OutgoingFileMessage> getFileMessages()
+ public synchronized Collection<OutgoingStreamMessage> getFileMessages()
{
// We may race between queuing all those messages and the completion of the completion of
// the first ones. So copy the values to avoid a ConcurrentModificationException
- return new ArrayList<>(files.values());
+ return new ArrayList<>(streams.values());
}
- public synchronized OutgoingFileMessage createMessageForRetry(int sequenceNumber)
+ public synchronized OutgoingStreamMessage createMessageForRetry(int sequenceNumber)
{
// remove previous time out task to be rescheduled later
ScheduledFuture future = timeoutTasks.remove(sequenceNumber);
if (future != null)
future.cancel(false);
- return files.get(sequenceNumber);
+ return streams.get(sequenceNumber);
}
/**
- * Schedule timeout task to release reference for file sent.
+ * Schedule timeout task to release reference for stream sent.
* When not receiving ACK after sending to receiver in given time,
* the task will release reference.
*
- * @param sequenceNumber sequence number of file sent.
+ * @param sequenceNumber sequence number of stream sent.
* @param time time to timeout
* @param unit unit of given time
* @return scheduled future for timeout task
*/
public synchronized ScheduledFuture scheduleTimeout(final int sequenceNumber, long time, TimeUnit unit)
{
- if (!files.containsKey(sequenceNumber))
+ if (!streams.containsKey(sequenceNumber))
return null;
ScheduledFuture future = timeoutExecutor.schedule(new Runnable()
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/StreamWriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/StreamWriter.java b/src/java/org/apache/cassandra/streaming/StreamWriter.java
deleted file mode 100644
index 81b3d8a..0000000
--- a/src/java/org/apache/cassandra/streaming/StreamWriter.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.Collection;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.cassandra.io.sstable.Component;
-import org.apache.cassandra.io.sstable.format.SSTableReader;
-import org.apache.cassandra.io.util.ChannelProxy;
-import org.apache.cassandra.io.util.DataIntegrityMetadata;
-import org.apache.cassandra.io.util.DataIntegrityMetadata.ChecksumValidator;
-import org.apache.cassandra.io.util.DataOutputStreamPlus;
-import org.apache.cassandra.io.util.FileUtils;
-import org.apache.cassandra.streaming.StreamManager.StreamRateLimiter;
-import org.apache.cassandra.streaming.compress.ByteBufCompressionDataOutputStreamPlus;
-import org.apache.cassandra.utils.FBUtilities;
-import org.apache.cassandra.utils.Pair;
-
-/**
- * StreamWriter writes given section of the SSTable to given channel.
- */
-public class StreamWriter
-{
- private static final int DEFAULT_CHUNK_SIZE = 64 * 1024;
-
- private static final Logger logger = LoggerFactory.getLogger(StreamWriter.class);
-
- protected final SSTableReader sstable;
- protected final Collection<Pair<Long, Long>> sections;
- protected final StreamRateLimiter limiter;
- protected final StreamSession session;
-
- public StreamWriter(SSTableReader sstable, Collection<Pair<Long, Long>> sections, StreamSession session)
- {
- this.session = session;
- this.sstable = sstable;
- this.sections = sections;
- this.limiter = StreamManager.getRateLimiter(session.peer);
- }
-
- /**
- * Stream file of specified sections to given channel.
- *
- * StreamWriter uses LZF compression on wire to decrease size to transfer.
- *
- * @param output where this writes data to
- * @throws IOException on any I/O error
- */
- public void write(DataOutputStreamPlus output) throws IOException
- {
- long totalSize = totalSize();
- logger.debug("[Stream #{}] Start streaming file {} to {}, repairedAt = {}, totalSize = {}", session.planId(),
- sstable.getFilename(), session.peer, sstable.getSSTableMetadata().repairedAt, totalSize);
-
- try(ChannelProxy proxy = sstable.getDataChannel().sharedCopy();
- ChecksumValidator validator = new File(sstable.descriptor.filenameFor(Component.CRC)).exists()
- ? DataIntegrityMetadata.checksumValidator(sstable.descriptor)
- : null)
- {
- int bufferSize = validator == null ? DEFAULT_CHUNK_SIZE: validator.chunkSize;
-
- // setting up data compression stream
- long progress = 0L;
-
- try (DataOutputStreamPlus compressedOutput = new ByteBufCompressionDataOutputStreamPlus(output, limiter))
- {
- // stream each of the required sections of the file
- for (Pair<Long, Long> section : sections)
- {
- long start = validator == null ? section.left : validator.chunkStart(section.left);
- // if the transfer does not start on the valididator's chunk boundary, this is the number of bytes to offset by
- int transferOffset = (int) (section.left - start);
- if (validator != null)
- validator.seek(start);
-
- // length of the section to read
- long length = section.right - start;
- // tracks write progress
- long bytesRead = 0;
- while (bytesRead < length)
- {
- int toTransfer = (int) Math.min(bufferSize, length - bytesRead);
- long lastBytesRead = write(proxy, validator, compressedOutput, start, transferOffset, toTransfer, bufferSize);
- start += lastBytesRead;
- bytesRead += lastBytesRead;
- progress += (lastBytesRead - transferOffset);
- session.progress(sstable.descriptor.filenameFor(Component.DATA), ProgressInfo.Direction.OUT, progress, totalSize);
- transferOffset = 0;
- }
-
- // make sure that current section is sent
- output.flush();
- }
- logger.debug("[Stream #{}] Finished streaming file {} to {}, bytesTransferred = {}, totalSize = {}",
- session.planId(), sstable.getFilename(), session.peer, FBUtilities.prettyPrintMemory(progress), FBUtilities.prettyPrintMemory(totalSize));
- }
- }
- }
-
- protected long totalSize()
- {
- long size = 0;
- for (Pair<Long, Long> section : sections)
- size += section.right - section.left;
- return size;
- }
-
- /**
- * Sequentially read bytes from the file and write them to the output stream
- *
- * @param proxy The file reader to read from
- * @param validator validator to verify data integrity
- * @param start The readd offset from the beginning of the {@code proxy} file.
- * @param transferOffset number of bytes to skip transfer, but include for validation.
- * @param toTransfer The number of bytes to be transferred.
- *
- * @return Number of bytes transferred.
- *
- * @throws java.io.IOException on any I/O error
- */
- protected long write(ChannelProxy proxy, ChecksumValidator validator, DataOutputStreamPlus output, long start, int transferOffset, int toTransfer, int bufferSize) throws IOException
- {
- // the count of bytes to read off disk
- int minReadable = (int) Math.min(bufferSize, proxy.size() - start);
-
- // this buffer will hold the data from disk. as it will be compressed on the fly by
- // ByteBufCompressionDataOutputStreamPlus.write(ByteBuffer), we can release this buffer as soon as we can.
- ByteBuffer buffer = ByteBuffer.allocateDirect(minReadable);
- try
- {
- int readCount = proxy.read(buffer, start);
- assert readCount == minReadable : String.format("could not read required number of bytes from file to be streamed: read %d bytes, wanted %d bytes", readCount, minReadable);
- buffer.flip();
-
- if (validator != null)
- {
- validator.validate(buffer);
- buffer.flip();
- }
-
- buffer.position(transferOffset);
- buffer.limit(transferOffset + (toTransfer - transferOffset));
- output.write(buffer);
- }
- finally
- {
- FileUtils.clean(buffer);
- }
-
- return toTransfer;
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/TableStreamManager.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/TableStreamManager.java b/src/java/org/apache/cassandra/streaming/TableStreamManager.java
new file mode 100644
index 0000000..11512e9
--- /dev/null
+++ b/src/java/org/apache/cassandra/streaming/TableStreamManager.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.streaming;
+
+import java.util.Collection;
+import java.util.UUID;
+
+import org.apache.cassandra.dht.Range;
+import org.apache.cassandra.dht.Token;
+import org.apache.cassandra.streaming.messages.StreamMessageHeader;
+
+/**
+ * The main streaming hook for a storage implementation.
+ *
+ * From here, the streaming system can get instances of {@link StreamReceiver}, {@link IncomingStream},
+ * and {@link OutgoingStream}, which expose the interfaces into the the underlying storage implementation
+ * needed to make streaming work.
+ */
+public interface TableStreamManager
+{
+ /**
+ * Creates a {@link StreamReceiver} for the given session, expecting the given number of streams
+ */
+ StreamReceiver createStreamReceiver(StreamSession session, int totalStreams);
+
+ /**
+ * Creates an {@link IncomingStream} for the given header
+ */
+ IncomingStream prepareIncomingStream(StreamSession session, StreamMessageHeader header);
+
+ /**
+ * Returns a collection of {@link OutgoingStream}s that contains the data selected by the
+ * given ranges, pendingRepair, and preview.
+ *
+ * There aren't any requirements on how data is divided between the outgoing streams
+ */
+ Collection<OutgoingStream> createOutgoingStreams(StreamSession session,
+ Collection<Range<Token>> ranges,
+ UUID pendingRepair,
+ PreviewKind previewKind);
+}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/async/NettyStreamingMessageSender.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/async/NettyStreamingMessageSender.java b/src/java/org/apache/cassandra/streaming/async/NettyStreamingMessageSender.java
index 20b7c87..bbc451d 100644
--- a/src/java/org/apache/cassandra/streaming/async/NettyStreamingMessageSender.java
+++ b/src/java/org/apache/cassandra/streaming/async/NettyStreamingMessageSender.java
@@ -55,28 +55,28 @@ import org.apache.cassandra.net.async.OutboundConnectionIdentifier;
import org.apache.cassandra.streaming.StreamConnectionFactory;
import org.apache.cassandra.streaming.StreamSession;
import org.apache.cassandra.streaming.StreamingMessageSender;
-import org.apache.cassandra.streaming.messages.IncomingFileMessage;
+import org.apache.cassandra.streaming.messages.IncomingStreamMessage;
import org.apache.cassandra.streaming.messages.KeepAliveMessage;
-import org.apache.cassandra.streaming.messages.OutgoingFileMessage;
+import org.apache.cassandra.streaming.messages.OutgoingStreamMessage;
import org.apache.cassandra.streaming.messages.StreamInitMessage;
import org.apache.cassandra.streaming.messages.StreamMessage;
import org.apache.cassandra.utils.FBUtilities;
/**
* Responsible for sending {@link StreamMessage}s to a given peer. We manage an array of netty {@link Channel}s
- * for sending {@link OutgoingFileMessage} instances; all other {@link StreamMessage} types are sent via
+ * for sending {@link OutgoingStreamMessage} instances; all other {@link StreamMessage} types are sent via
* a special control channel. The reason for this is to treat those messages carefully and not let them get stuck
- * behind a file transfer.
+ * behind a stream transfer.
*
- * One of the challenges when sending files is we might need to delay shipping the file if:
+ * One of the challenges when sending streams is we might need to delay shipping the stream if:
*
* - we've exceeded our network I/O use due to rate limiting (at the cassandra level)
* - the receiver isn't keeping up, which causes the local TCP socket buffer to not empty, which causes epoll writes to not
* move any bytes to the socket, which causes buffers to stick around in user-land (a/k/a cassandra) memory.
*
- * When those conditions occur, it's easy enough to reschedule processing the file once the resources pick up
+ * When those conditions occur, it's easy enough to reschedule processing the stream once the resources pick up
* (we acquire the permits from the rate limiter, or the socket drains). However, we need to ensure that
- * no other messages are submitted to the same channel while the current file is still being processed.
+ * no other messages are submitted to the same channel while the current stream is still being processed.
*/
public class NettyStreamingMessageSender implements StreamingMessageSender
{
@@ -97,8 +97,8 @@ public class NettyStreamingMessageSender implements StreamingMessageSender
private volatile boolean closed;
/**
- * A special {@link Channel} for sending non-file streaming messages, basically anything that isn't an
- * {@link OutgoingFileMessage} (or an {@link IncomingFileMessage}, but a node doesn't send that, it's only received).
+ * A special {@link Channel} for sending non-stream streaming messages, basically anything that isn't an
+ * {@link OutgoingStreamMessage} (or an {@link IncomingStreamMessage}, but a node doesn't send that, it's only received).
*/
private Channel controlMessageChannel;
@@ -113,9 +113,9 @@ public class NettyStreamingMessageSender implements StreamingMessageSender
private final ConcurrentMap<Thread, Channel> threadToChannelMap = new ConcurrentHashMap<>();
/**
- * A netty channel attribute used to indicate if a channel is currently transferring a file. This is primarily used
+ * A netty channel attribute used to indicate if a channel is currently transferring a stream. This is primarily used
* to indicate to the {@link KeepAliveTask} if it is safe to send a {@link KeepAliveMessage}, as sending the
- * (application level) keep-alive in the middle of streaming a file would be bad news.
+ * (application level) keep-alive in the middle of a stream would be bad news.
*/
@VisibleForTesting
static final AttributeKey<Boolean> TRANSFERRING_FILE_ATTR = AttributeKey.valueOf("transferringFile");
@@ -141,7 +141,6 @@ public class NettyStreamingMessageSender implements StreamingMessageSender
session.sessionIndex(),
session.planId(),
session.streamOperation(),
- session.keepSSTableLevel(),
session.getPendingRepair(),
session.getPreviewKind());
sendMessage(message);
@@ -209,12 +208,12 @@ public class NettyStreamingMessageSender implements StreamingMessageSender
if (closed)
throw new RuntimeException("stream has been closed, cannot send " + message);
- if (message instanceof OutgoingFileMessage)
+ if (message instanceof OutgoingStreamMessage)
{
if (isPreview)
- throw new RuntimeException("Cannot send file messages for preview streaming sessions");
+ throw new RuntimeException("Cannot send stream data messages for preview streaming sessions");
logger.debug("{} Sending {}", createLogTag(session, null), message);
- fileTransferExecutor.submit(new FileStreamTask((OutgoingFileMessage)message));
+ fileTransferExecutor.submit(new FileStreamTask((OutgoingStreamMessage)message));
return;
}
@@ -271,7 +270,7 @@ public class NettyStreamingMessageSender implements StreamingMessageSender
return null;
Channel channel = channelFuture.channel();
- logger.error("{} failed to send a stream message/file to peer {}: msg = {}",
+ logger.error("{} failed to send a stream message/data to peer {}: msg = {}",
createLogTag(session, channel), connectionId, msg, future.cause());
// StreamSession will invoke close(), but we have to mark this sender as closed so the session doesn't try
@@ -288,12 +287,12 @@ public class NettyStreamingMessageSender implements StreamingMessageSender
private static final int SEMAPHORE_UNAVAILABLE_LOG_INTERVAL = 3;
/**
- * Even though we expect only an {@link OutgoingFileMessage} at runtime, the type here is {@link StreamMessage}
+ * Even though we expect only an {@link OutgoingStreamMessage} at runtime, the type here is {@link StreamMessage}
* to facilitate simpler testing.
*/
private final StreamMessage msg;
- FileStreamTask(OutgoingFileMessage ofm)
+ FileStreamTask(OutgoingStreamMessage ofm)
{
this.msg = ofm;
}
@@ -357,9 +356,9 @@ public class NettyStreamingMessageSender implements StreamingMessageSender
if (now - timeOfLastLogging > logIntervalNanos)
{
timeOfLastLogging = now;
- OutgoingFileMessage ofm = (OutgoingFileMessage)msg;
- logger.info("{} waiting to acquire a permit to begin streaming file {}. This message logs every {} minutes",
- createLogTag(session, null), ofm.getFilename(), logInterval);
+ OutgoingStreamMessage ofm = (OutgoingStreamMessage)msg;
+ logger.info("{} waiting to acquire a permit to begin streaming {}. This message logs every {} minutes",
+ createLogTag(session, null), ofm.getName(), logInterval);
}
}
catch (InterruptedException ie)
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/async/StreamingInboundHandler.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/async/StreamingInboundHandler.java b/src/java/org/apache/cassandra/streaming/async/StreamingInboundHandler.java
index 907572b..03f0640 100644
--- a/src/java/org/apache/cassandra/streaming/async/StreamingInboundHandler.java
+++ b/src/java/org/apache/cassandra/streaming/async/StreamingInboundHandler.java
@@ -20,7 +20,6 @@ package org.apache.cassandra.streaming.async;
import java.io.EOFException;
import java.io.IOException;
-import java.net.InetAddress;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@@ -43,8 +42,8 @@ import org.apache.cassandra.streaming.StreamManager;
import org.apache.cassandra.streaming.StreamReceiveException;
import org.apache.cassandra.streaming.StreamResultFuture;
import org.apache.cassandra.streaming.StreamSession;
-import org.apache.cassandra.streaming.messages.FileMessageHeader;
-import org.apache.cassandra.streaming.messages.IncomingFileMessage;
+import org.apache.cassandra.streaming.messages.StreamMessageHeader;
+import org.apache.cassandra.streaming.messages.IncomingStreamMessage;
import org.apache.cassandra.streaming.messages.KeepAliveMessage;
import org.apache.cassandra.streaming.messages.StreamInitMessage;
import org.apache.cassandra.streaming.messages.StreamMessage;
@@ -53,8 +52,8 @@ import org.apache.cassandra.utils.JVMStabilityInspector;
import static org.apache.cassandra.streaming.async.NettyStreamingMessageSender.createLogTag;
/**
- * Handles the inbound side of streaming messages and sstable data. From the incoming data, we derserialize the message
- * and potentially reify partitions and rows and write those out to new sstable files. Because deserialization is a blocking affair,
+ * Handles the inbound side of streaming messages and stream data. From the incoming data, we derserialize the message
+ * including the actual stream data itself. Because the reading and deserialization of streams is a blocking affair,
* we can't block the netty event loop. Thus we have a background thread perform all the blocking deserialization.
*/
public class StreamingInboundHandler extends ChannelInboundHandlerAdapter
@@ -128,7 +127,7 @@ public class StreamingInboundHandler extends ChannelInboundHandlerAdapter
if (cause instanceof IOException)
logger.trace("connection problem while streaming", cause);
else
- logger.warn("exception occurred while in processing streaming file", cause);
+ logger.warn("exception occurred while in processing streaming data", cause);
close();
}
@@ -224,20 +223,20 @@ public class StreamingInboundHandler extends ChannelInboundHandlerAdapter
StreamSession deriveSession(StreamMessage message) throws IOException
{
StreamSession streamSession = null;
- // StreamInitMessage starts a new channel, and IncomingFileMessage potentially, as well.
- // IncomingFileMessage needs a session to be established a priori, though
+ // StreamInitMessage starts a new channel, and IncomingStreamMessage potentially, as well.
+ // IncomingStreamMessage needs a session to be established a priori, though
if (message instanceof StreamInitMessage)
{
assert session == null : "initiator of stream session received a StreamInitMessage";
StreamInitMessage init = (StreamInitMessage) message;
- StreamResultFuture.initReceivingSide(init.sessionIndex, init.planId, init.streamOperation, init.from, channel, init.keepSSTableLevel, init.pendingRepair, init.previewKind);
+ StreamResultFuture.initReceivingSide(init.sessionIndex, init.planId, init.streamOperation, init.from, channel, init.pendingRepair, init.previewKind);
streamSession = sessionProvider.apply(new SessionIdentifier(init.from, init.planId, init.sessionIndex));
}
- else if (message instanceof IncomingFileMessage)
+ else if (message instanceof IncomingStreamMessage)
{
- // TODO: it'd be great to check if the session actually exists before slurping in the entire sstable,
+ // TODO: it'd be great to check if the session actually exists before slurping in the entire stream,
// but that's a refactoring for another day
- FileMessageHeader header = ((IncomingFileMessage) message).header;
+ StreamMessageHeader header = ((IncomingStreamMessage) message).header;
streamSession = sessionProvider.apply(new SessionIdentifier(header.sender, header.planId, header.sessionIndex));
}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/async/package-info.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/async/package-info.java b/src/java/org/apache/cassandra/streaming/async/package-info.java
index ecf5115..9455c7c 100644
--- a/src/java/org/apache/cassandra/streaming/async/package-info.java
+++ b/src/java/org/apache/cassandra/streaming/async/package-info.java
@@ -18,14 +18,14 @@
/**
* <h1>Non-blocking streaming with netty</h1>
- * This document describes the implementation details of streaming protocol. A listener for a streaming
+ * This document describes the implementation details of the streaming protocol. A listener for a streaming
* session listens on the same socket as internode messaging, and participates in the same handshake protocol
* That protocol is described in the package-level documentation for {@link org.apache.cassandra.net.async}, and
* thus not here.
*
* Streaming 2.0 was implemented as CASSANDRA-5286. Streaming 2.0 used (the equivalent of) a single thread and
* a single socket to transfer sstables sequentially to a peer (either as part of a repair, bootstrap, and so on).
- * Part of the motivation for switching to netty and a non-blocking model as to enable file transfers to occur
+ * Part of the motivation for switching to netty and a non-blocking model as to enable stream transfers to occur
* in parallel for a given session.
*
* Thus, a more detailed approach is required for stream session management.
@@ -34,38 +34,6 @@
*
* The full details of the session lifecycle are documented in {@link org.apache.cassandra.streaming.StreamSession}.
*
- *
- * <h2>File transfer</h2>
- *
- * When tranferring whole or subsections of an sstable, only the DATA component is shipped. To that end,
- * there are three "modes" of an sstable transfer that need to be handled somewhat differently:
- *
- * 1) uncompressed sstable - data needs to be read into user space so it can be manipulated: checksum validation,
- * apply stream compression (see next section), and/or TLS encryption.
- *
- * 2) compressed sstable, transferred with SSL/TLS - data needs to be read into user space as that is where the TLS encryption
- * needs to happen. Netty does not allow the pretense of doing zero-copy transfers when TLS is in the pipeline;
- * data must explicitly be pulled into user-space memory for TLS encryption to work.
- *
- * 3) compressed sstable, transferred without SSL/TLS - data can be streamed via zero-copy transfer as the data does not
- * need to be manipulated (it can be sent "as-is").
- *
- * <h3>Compressing the data</h3>
- * We always want to transfer as few bytes as possible of the wire when streaming a file. If the
- * sstable is not already compressed via table compression options, we apply an on-the-fly stream compression
- * to the data. The stream compression format is documented in
- * {@link org.apache.cassandra.streaming.async.StreamCompressionSerializer}
- *
- * You may be wondering: why implement your own compression scheme? why not use netty's built-in compression codecs,
- * like {@link io.netty.handler.codec.compression.Lz4FrameEncoder}? That makes complete sense if all the sstables
- * to be streamed are non using sstable compression (and obviously you wouldn't use stream compression when the sstables
- * are using sstable compression). The problem is when you have a mix of files, some using sstable compression
- * and some not. You can either:
- *
- * - send the files of one type over one kind of socket, and the others over another socket
- * - send them both over the same socket, but then auto-adjust per each file type.
- *
- * I've opted for the latter to keep socket/channel management simpler and cleaner.
*/
package org.apache.cassandra.streaming.async;
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/compress/CompressedInputStream.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/compress/CompressedInputStream.java b/src/java/org/apache/cassandra/streaming/compress/CompressedInputStream.java
deleted file mode 100644
index 290dd9e..0000000
--- a/src/java/org/apache/cassandra/streaming/compress/CompressedInputStream.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming.compress;
-
-import java.io.EOFException;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.ReadableByteChannel;
-import java.util.Iterator;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ThreadLocalRandom;
-import java.util.function.DoubleSupplier;
-
-import com.google.common.collect.Iterators;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import io.netty.util.concurrent.FastThreadLocalThread;
-import org.apache.cassandra.io.compress.CompressionMetadata;
-import org.apache.cassandra.io.util.DataInputPlus;
-import org.apache.cassandra.io.util.FileUtils;
-import org.apache.cassandra.io.util.RebufferingInputStream;
-import org.apache.cassandra.streaming.StreamReader.StreamDeserializer;
-import org.apache.cassandra.utils.ChecksumType;
-import org.apache.cassandra.utils.WrappedRunnable;
-
-/**
- * InputStream which reads data from underlining source with given {@link CompressionInfo}. Uses {@link #buffer} as a buffer
- * for uncompressed data (which is read by stream consumers - {@link StreamDeserializer} in this case).
- */
-public class CompressedInputStream extends RebufferingInputStream implements AutoCloseable
-{
-
- private static final Logger logger = LoggerFactory.getLogger(CompressedInputStream.class);
-
- private final CompressionInfo info;
- // chunk buffer
- private final BlockingQueue<ByteBuffer> dataBuffer;
- private final DoubleSupplier crcCheckChanceSupplier;
-
- /**
- * The base offset of the current {@link #buffer} from the beginning of the stream.
- */
- private long bufferOffset = 0;
-
- /**
- * The current {@link CompressedStreamReader#sections} offset in the stream.
- */
- private long current = 0;
-
- private final ChecksumType checksumType;
-
- private static final int CHECKSUM_LENGTH = 4;
-
- /**
- * Indicates there was a problem when reading from source stream.
- * When this is added to the <code>dataBuffer</code> by the stream Reader,
- * it is expected that the <code>readException</code> variable is populated
- * with the cause of the error when reading from source stream, so it is
- * thrown to the consumer on subsequent read operation.
- */
- private static final ByteBuffer POISON_PILL = ByteBuffer.wrap(new byte[0]);
-
- private volatile IOException readException = null;
-
- private long totalCompressedBytesRead;
-
- /**
- * @param source Input source to read compressed data from
- * @param info Compression info
- */
- public CompressedInputStream(DataInputPlus source, CompressionInfo info, ChecksumType checksumType, DoubleSupplier crcCheckChanceSupplier)
- {
- super(ByteBuffer.allocateDirect(info.parameters.chunkLength()));
- buffer.limit(buffer.position()); // force the buffer to appear "consumed" so that it triggers reBuffer on the first read
- this.info = info;
- this.dataBuffer = new ArrayBlockingQueue<>(Math.min(info.chunks.length, 1024));
- this.crcCheckChanceSupplier = crcCheckChanceSupplier;
- this.checksumType = checksumType;
-
- new FastThreadLocalThread(new Reader(source, info, dataBuffer)).start();
- }
-
- /**
- * Invoked when crossing into the next stream boundary in {@link CompressedStreamReader#sections}.
- */
- public void position(long position) throws IOException
- {
- if (readException != null)
- throw readException;
-
- assert position >= current : "stream can only read forward.";
- current = position;
-
- if (current > bufferOffset + buffer.limit())
- reBuffer(false);
-
- buffer.position((int)(current - bufferOffset));
- }
-
- protected void reBuffer() throws IOException
- {
- reBuffer(true);
- }
-
- private void reBuffer(boolean updateCurrent) throws IOException
- {
- if (readException != null)
- {
- FileUtils.clean(buffer);
- buffer = null;
- throw readException;
- }
-
- // increment the offset into the stream based on the current buffer's read count
- if (updateCurrent)
- current += buffer.position();
-
- try
- {
- ByteBuffer compressedWithCRC = dataBuffer.take();
- if (compressedWithCRC == POISON_PILL)
- {
- assert readException != null;
- throw readException;
- }
-
- decompress(compressedWithCRC);
- }
- catch (InterruptedException e)
- {
- throw new EOFException("No chunk available");
- }
- }
-
- private void decompress(ByteBuffer compressed) throws IOException
- {
- int length = compressed.remaining();
-
- // uncompress if the buffer size is less than the max chunk size. else, if the buffer size is greater than or equal to the maxCompressedLength,
- // we assume the buffer is not compressed. see CASSANDRA-10520
- final boolean releaseCompressedBuffer;
- if (length - CHECKSUM_LENGTH < info.parameters.maxCompressedLength())
- {
- buffer.clear();
- compressed.limit(length - CHECKSUM_LENGTH);
- info.parameters.getSstableCompressor().uncompress(compressed, buffer);
- buffer.flip();
- releaseCompressedBuffer = true;
- }
- else
- {
- FileUtils.clean(buffer);
- buffer = compressed;
- buffer.limit(length - CHECKSUM_LENGTH);
- releaseCompressedBuffer = false;
- }
- totalCompressedBytesRead += length;
-
- // validate crc randomly
- double crcCheckChance = this.crcCheckChanceSupplier.getAsDouble();
- if (crcCheckChance >= 1d ||
- (crcCheckChance > 0d && crcCheckChance > ThreadLocalRandom.current().nextDouble()))
- {
- ByteBuffer crcBuf = compressed.duplicate();
- crcBuf.limit(length - CHECKSUM_LENGTH).position(0);
- int checksum = (int) checksumType.of(crcBuf);
-
- crcBuf.limit(length);
- if (crcBuf.getInt() != checksum)
- throw new IOException("CRC unmatched");
- }
-
- if (releaseCompressedBuffer)
- FileUtils.clean(compressed);
-
- // buffer offset is always aligned
- final int compressedChunkLength = info.parameters.chunkLength();
- bufferOffset = current & ~(compressedChunkLength - 1);
- }
-
- public long getTotalCompressedBytesRead()
- {
- return totalCompressedBytesRead;
- }
-
- /**
- * {@inheritDoc}
- *
- * Releases the resources specific to this instance, but not the {@link DataInputPlus} that is used by the {@link Reader}.
- */
- @Override
- public void close()
- {
- if (buffer != null)
- {
- FileUtils.clean(buffer);
- buffer = null;
- }
- }
-
- class Reader extends WrappedRunnable
- {
- private final DataInputPlus source;
- private final Iterator<CompressionMetadata.Chunk> chunks;
- private final BlockingQueue<ByteBuffer> dataBuffer;
-
- Reader(DataInputPlus source, CompressionInfo info, BlockingQueue<ByteBuffer> dataBuffer)
- {
- this.source = source;
- this.chunks = Iterators.forArray(info.chunks);
- this.dataBuffer = dataBuffer;
- }
-
- protected void runMayThrow() throws Exception
- {
- byte[] tmp = null;
- while (chunks.hasNext())
- {
- CompressionMetadata.Chunk chunk = chunks.next();
-
- int readLength = chunk.length + 4; // read with CRC
- ByteBuffer compressedWithCRC = null;
- try
- {
- final int r;
- if (source instanceof ReadableByteChannel)
- {
- compressedWithCRC = ByteBuffer.allocateDirect(readLength);
- r = ((ReadableByteChannel)source).read(compressedWithCRC);
- compressedWithCRC.flip();
- }
- else
- {
- // read into an on-heap araay, then copy over to an off-heap buffer. at a minumum snappy requires
- // off-heap buffers for decompression, else we could have just wrapped the plain byte array in a ByteBuffer
- if (tmp == null || tmp.length < info.parameters.chunkLength() + CHECKSUM_LENGTH)
- tmp = new byte[info.parameters.chunkLength() + CHECKSUM_LENGTH];
- source.readFully(tmp, 0, readLength);
- compressedWithCRC = ByteBuffer.allocateDirect(readLength);
- compressedWithCRC.put(tmp, 0, readLength);
- compressedWithCRC.position(0);
- r = readLength;
- }
-
- if (r < 0)
- {
- FileUtils.clean(compressedWithCRC);
- readException = new EOFException("No chunk available");
- dataBuffer.put(POISON_PILL);
- return; // throw exception where we consume dataBuffer
- }
- }
- catch (IOException e)
- {
- if (!(e instanceof EOFException))
- logger.warn("Error while reading compressed input stream.", e);
- if (compressedWithCRC != null)
- FileUtils.clean(compressedWithCRC);
-
- readException = e;
- dataBuffer.put(POISON_PILL);
- return; // throw exception where we consume dataBuffer
- }
- dataBuffer.put(compressedWithCRC);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/compress/CompressedStreamReader.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/compress/CompressedStreamReader.java b/src/java/org/apache/cassandra/streaming/compress/CompressedStreamReader.java
deleted file mode 100644
index bd44209..0000000
--- a/src/java/org/apache/cassandra/streaming/compress/CompressedStreamReader.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming.compress;
-
-import java.io.IOException;
-
-import com.google.common.base.Throwables;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.cassandra.db.ColumnFamilyStore;
-import org.apache.cassandra.io.compress.CompressionMetadata;
-import org.apache.cassandra.io.sstable.SSTableMultiWriter;
-import org.apache.cassandra.io.util.DataInputPlus;
-import org.apache.cassandra.io.util.TrackedDataInputPlus;
-import org.apache.cassandra.streaming.ProgressInfo;
-import org.apache.cassandra.streaming.StreamReader;
-import org.apache.cassandra.streaming.StreamSession;
-import org.apache.cassandra.streaming.messages.FileMessageHeader;
-import org.apache.cassandra.utils.ChecksumType;
-import org.apache.cassandra.utils.FBUtilities;
-import org.apache.cassandra.utils.Pair;
-
-import static org.apache.cassandra.utils.Throwables.extractIOExceptionCause;
-
-/**
- * StreamReader that reads from streamed compressed SSTable
- */
-public class CompressedStreamReader extends StreamReader
-{
- private static final Logger logger = LoggerFactory.getLogger(CompressedStreamReader.class);
-
- protected final CompressionInfo compressionInfo;
-
- public CompressedStreamReader(FileMessageHeader header, StreamSession session)
- {
- super(header, session);
- this.compressionInfo = header.compressionInfo;
- }
-
- /**
- * @return SSTable transferred
- * @throws java.io.IOException if reading the remote sstable fails. Will throw an RTE if local write fails.
- */
- @Override
- @SuppressWarnings("resource") // input needs to remain open, streams on top of it can't be closed
- public SSTableMultiWriter read(DataInputPlus inputPlus) throws IOException
- {
- long totalSize = totalSize();
-
- ColumnFamilyStore cfs = ColumnFamilyStore.getIfExists(tableId);
-
- if (cfs == null)
- {
- // schema was dropped during streaming
- throw new IOException("CF " + tableId + " was dropped during streaming");
- }
-
- logger.debug("[Stream #{}] Start receiving file #{} from {}, repairedAt = {}, size = {}, ks = '{}', pendingRepair = '{}', table = '{}'.",
- session.planId(), fileSeqNum, session.peer, repairedAt, totalSize, cfs.keyspace.getName(), pendingRepair,
- cfs.getTableName());
-
- StreamDeserializer deserializer = null;
- SSTableMultiWriter writer = null;
- try (CompressedInputStream cis = new CompressedInputStream(inputPlus, compressionInfo, ChecksumType.CRC32, cfs::getCrcCheckChance))
- {
- TrackedDataInputPlus in = new TrackedDataInputPlus(cis);
- deserializer = new StreamDeserializer(cfs.metadata(), in, inputVersion, getHeader(cfs.metadata()));
- writer = createWriter(cfs, totalSize, repairedAt, pendingRepair, format);
- String filename = writer.getFilename();
- int sectionIdx = 0;
- for (Pair<Long, Long> section : sections)
- {
- assert cis.getTotalCompressedBytesRead() <= totalSize;
- long sectionLength = section.right - section.left;
-
- logger.trace("[Stream #{}] Reading section {} with length {} from stream.", session.planId(), sectionIdx++, sectionLength);
- // skip to beginning of section inside chunk
- cis.position(section.left);
- in.reset(0);
-
- while (in.getBytesRead() < sectionLength)
- {
- writePartition(deserializer, writer);
- // when compressed, report total bytes of compressed chunks read since remoteFile.size is the sum of chunks transferred
- session.progress(filename, ProgressInfo.Direction.IN, cis.getTotalCompressedBytesRead(), totalSize);
- }
- }
- logger.debug("[Stream #{}] Finished receiving file #{} from {} readBytes = {}, totalSize = {}", session.planId(), fileSeqNum,
- session.peer, FBUtilities.prettyPrintMemory(cis.getTotalCompressedBytesRead()), FBUtilities.prettyPrintMemory(totalSize));
- return writer;
- }
- catch (Throwable e)
- {
- Object partitionKey = deserializer != null ? deserializer.partitionKey() : "";
- logger.warn("[Stream {}] Error while reading partition {} from stream on ks='{}' and table='{}'.",
- session.planId(), partitionKey, cfs.keyspace.getName(), cfs.getTableName());
- if (writer != null)
- {
- writer.abort(e);
- }
- if (extractIOExceptionCause(e).isPresent())
- throw e;
- throw Throwables.propagate(e);
- }
- }
-
- @Override
- protected long totalSize()
- {
- long size = 0;
- // calculate total length of transferring chunks
- for (CompressionMetadata.Chunk chunk : compressionInfo.chunks)
- size += chunk.length + 4; // 4 bytes for CRC
- return size;
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/compress/CompressedStreamWriter.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/compress/CompressedStreamWriter.java b/src/java/org/apache/cassandra/streaming/compress/CompressedStreamWriter.java
deleted file mode 100644
index 0e78b7d..0000000
--- a/src/java/org/apache/cassandra/streaming/compress/CompressedStreamWriter.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming.compress;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.apache.cassandra.io.compress.CompressionMetadata;
-import org.apache.cassandra.io.sstable.Component;
-import org.apache.cassandra.io.sstable.format.SSTableReader;
-import org.apache.cassandra.io.util.ChannelProxy;
-import org.apache.cassandra.io.util.DataOutputStreamPlus;
-import org.apache.cassandra.io.util.FileUtils;
-import org.apache.cassandra.net.async.ByteBufDataOutputStreamPlus;
-import org.apache.cassandra.streaming.ProgressInfo;
-import org.apache.cassandra.streaming.StreamSession;
-import org.apache.cassandra.streaming.StreamWriter;
-import org.apache.cassandra.utils.FBUtilities;
-import org.apache.cassandra.utils.Pair;
-
-/**
- * StreamWriter for compressed SSTable.
- */
-public class CompressedStreamWriter extends StreamWriter
-{
- private static final int CHUNK_SIZE = 1 << 16;
-
- private static final Logger logger = LoggerFactory.getLogger(CompressedStreamWriter.class);
-
- private final CompressionInfo compressionInfo;
-
- public CompressedStreamWriter(SSTableReader sstable, Collection<Pair<Long, Long>> sections, CompressionInfo compressionInfo, StreamSession session)
- {
- super(sstable, sections, session);
- this.compressionInfo = compressionInfo;
- }
-
- @Override
- public void write(DataOutputStreamPlus out) throws IOException
- {
- assert out instanceof ByteBufDataOutputStreamPlus;
- ByteBufDataOutputStreamPlus output = (ByteBufDataOutputStreamPlus)out;
- long totalSize = totalSize();
- logger.debug("[Stream #{}] Start streaming file {} to {}, repairedAt = {}, totalSize = {}", session.planId(),
- sstable.getFilename(), session.peer, sstable.getSSTableMetadata().repairedAt, totalSize);
- try (ChannelProxy fc = sstable.getDataChannel().sharedCopy())
- {
- long progress = 0L;
- // calculate chunks to transfer. we want to send continuous chunks altogether.
- List<Pair<Long, Long>> sections = getTransferSections(compressionInfo.chunks);
-
- int sectionIdx = 0;
-
- // stream each of the required sections of the file
- for (final Pair<Long, Long> section : sections)
- {
- // length of the section to stream
- long length = section.right - section.left;
-
- logger.trace("[Stream #{}] Writing section {} with length {} to stream.", session.planId(), sectionIdx++, length);
-
- // tracks write progress
- long bytesTransferred = 0;
- while (bytesTransferred < length)
- {
- final int toTransfer = (int) Math.min(CHUNK_SIZE, length - bytesTransferred);
- limiter.acquire(toTransfer);
-
- ByteBuffer outBuffer = ByteBuffer.allocateDirect(toTransfer);
- long lastWrite;
- try
- {
- lastWrite = fc.read(outBuffer, section.left + bytesTransferred);
- assert lastWrite == toTransfer : String.format("could not read required number of bytes from file to be streamed: read %d bytes, wanted %d bytes", lastWrite, toTransfer);
- outBuffer.flip();
- output.writeToChannel(outBuffer);
- }
- catch (IOException e)
- {
- FileUtils.clean(outBuffer);
- throw e;
- }
-
- bytesTransferred += lastWrite;
- progress += lastWrite;
- session.progress(sstable.descriptor.filenameFor(Component.DATA), ProgressInfo.Direction.OUT, progress, totalSize);
- }
- }
- logger.debug("[Stream #{}] Finished streaming file {} to {}, bytesTransferred = {}, totalSize = {}",
- session.planId(), sstable.getFilename(), session.peer, FBUtilities.prettyPrintMemory(progress), FBUtilities.prettyPrintMemory(totalSize));
- }
- }
-
- @Override
- protected long totalSize()
- {
- long size = 0;
- // calculate total length of transferring chunks
- for (CompressionMetadata.Chunk chunk : compressionInfo.chunks)
- size += chunk.length + 4; // 4 bytes for CRC
- return size;
- }
-
- // chunks are assumed to be sorted by offset
- private List<Pair<Long, Long>> getTransferSections(CompressionMetadata.Chunk[] chunks)
- {
- List<Pair<Long, Long>> transferSections = new ArrayList<>();
- Pair<Long, Long> lastSection = null;
- for (CompressionMetadata.Chunk chunk : chunks)
- {
- if (lastSection != null)
- {
- if (chunk.offset == lastSection.right)
- {
- // extend previous section to end of this chunk
- lastSection = Pair.create(lastSection.left, chunk.offset + chunk.length + 4); // 4 bytes for CRC
- }
- else
- {
- transferSections.add(lastSection);
- lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4);
- }
- }
- else
- {
- lastSection = Pair.create(chunk.offset, chunk.offset + chunk.length + 4);
- }
- }
- if (lastSection != null)
- transferSections.add(lastSection);
- return transferSections;
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/compress/CompressionInfo.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/compress/CompressionInfo.java b/src/java/org/apache/cassandra/streaming/compress/CompressionInfo.java
deleted file mode 100644
index bd0c2d5..0000000
--- a/src/java/org/apache/cassandra/streaming/compress/CompressionInfo.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.cassandra.streaming.compress;
-
-import java.io.IOException;
-
-import org.apache.cassandra.db.TypeSizes;
-import org.apache.cassandra.io.IVersionedSerializer;
-import org.apache.cassandra.io.compress.CompressionMetadata;
-import org.apache.cassandra.schema.CompressionParams;
-import org.apache.cassandra.io.util.DataInputPlus;
-import org.apache.cassandra.io.util.DataOutputPlus;
-
-/**
- * Container that carries compression parameters and chunks to decompress data from stream.
- */
-public class CompressionInfo
-{
- public static final IVersionedSerializer<CompressionInfo> serializer = new CompressionInfoSerializer();
-
- public final CompressionMetadata.Chunk[] chunks;
- public final CompressionParams parameters;
-
- public CompressionInfo(CompressionMetadata.Chunk[] chunks, CompressionParams parameters)
- {
- assert chunks != null && parameters != null;
- this.chunks = chunks;
- this.parameters = parameters;
- }
-
- static class CompressionInfoSerializer implements IVersionedSerializer<CompressionInfo>
- {
- public void serialize(CompressionInfo info, DataOutputPlus out, int version) throws IOException
- {
- if (info == null)
- {
- out.writeInt(-1);
- return;
- }
-
- int chunkCount = info.chunks.length;
- out.writeInt(chunkCount);
- for (int i = 0; i < chunkCount; i++)
- CompressionMetadata.Chunk.serializer.serialize(info.chunks[i], out, version);
- // compression params
- CompressionParams.serializer.serialize(info.parameters, out, version);
- }
-
- public CompressionInfo deserialize(DataInputPlus in, int version) throws IOException
- {
- // chunks
- int chunkCount = in.readInt();
- if (chunkCount < 0)
- return null;
-
- CompressionMetadata.Chunk[] chunks = new CompressionMetadata.Chunk[chunkCount];
- for (int i = 0; i < chunkCount; i++)
- chunks[i] = CompressionMetadata.Chunk.serializer.deserialize(in, version);
-
- // compression params
- CompressionParams parameters = CompressionParams.serializer.deserialize(in, version);
- return new CompressionInfo(chunks, parameters);
- }
-
- public long serializedSize(CompressionInfo info, int version)
- {
- if (info == null)
- return TypeSizes.sizeof(-1);
-
- // chunks
- int chunkCount = info.chunks.length;
- long size = TypeSizes.sizeof(chunkCount);
- for (int i = 0; i < chunkCount; i++)
- size += CompressionMetadata.Chunk.serializer.serializedSize(info.chunks[i], version);
- // compression params
- size += CompressionParams.serializer.serializedSize(info.parameters, version);
- return size;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cassandra/blob/9714a7c8/src/java/org/apache/cassandra/streaming/management/ProgressInfoCompositeData.java
----------------------------------------------------------------------
diff --git a/src/java/org/apache/cassandra/streaming/management/ProgressInfoCompositeData.java b/src/java/org/apache/cassandra/streaming/management/ProgressInfoCompositeData.java
index 964fe10..a1fa19f 100644
--- a/src/java/org/apache/cassandra/streaming/management/ProgressInfoCompositeData.java
+++ b/src/java/org/apache/cassandra/streaming/management/ProgressInfoCompositeData.java
@@ -42,7 +42,7 @@ public class ProgressInfoCompositeData
"Session peer",
"Session peer storage port",
"Index of session",
- "Name of the file",
+ "Name of the stream",
"Direction('IN' or 'OUT')",
"Current bytes transferred",
"Total bytes to transfer"};
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org