jyothsnakonisa commented on code in PR #236:
URL:
https://github.com/apache/cassandra-analytics/pull/236#discussion_r3963484371
##########
cassandra-analytics-integration-tests/src/test/java/org/apache/cassandra/analytics/ResiliencyTestBase.java:
##########
@@ -59,6 +61,33 @@ public abstract class ResiliencyTestBase extends
SharedClusterSparkIntegrationTe
{
public static final String QUERY_ALL_ROWS = "SELECT * FROM %s";
+ /**
+ * Skips the test class when the version under test declares none of the
internals that the ByteBuddy hooks of a
+ * topology-change test intercept: {@code
StorageService.bootstrap(Collection, long)},
+ * {@code StorageService.unbootstrap()} and {@code
RangeRelocator.stream()}. CEP-21 Transactional Cluster Metadata
+ * removed all three in Cassandra 6.0, in favour of {@code
org.apache.cassandra.tcm.sequences}. A hook that fails
+ * to install is silent, so the test would instead wait on a latch that
never counts down.
+ *
+ * <p>Call this from {@link #beforeClusterProvisioning()}, which runs
before the cluster starts.</p>
+ */
+ protected void assumeTopologyChangeHooksSupported()
Review Comment:
This will skip several topology change related tests for 6.0 version
permanently. WDYT about re writing the tests with 6.0 equivalent way of removed
methods.
If you think that is too involved, we should consider doing a followup PR to
fix these tests. As a starting point, BootstrapAndJoin.bootstrap(...) and
UnbootstrapStreams.execute(...) look like reasonably direct replacements for
the old StorageService.bootstrap()/unbootstrap() hooks
##########
cassandra-analytics-common/src/main/java/org/apache/cassandra/bridge/CassandraVersionFeatures.java:
##########
@@ -32,7 +34,14 @@ public class CassandraVersionFeatures implements
Comparable<CassandraVersionFeat
{
private static final Pattern VERSION_PATTERN_3 =
Pattern.compile("(?:.+-)?([0-9]+)\\.([0-9]+)\\.([0-9]+)([a-zA-Z0-9-]*)");
private static final Pattern VERSION_PATTERN_4 =
Pattern.compile("(?:.+-)?([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)[a-zA-Z0-9-]*");
- private static final Pattern VERSION_PATTERN_SNAPSHOT =
Pattern.compile("(?:.+-)?([0-9]+)\\.([0-9]+)-(SNAPSHOT)$");
+ // A major version carries no patch number until its first release:
cassandra-4.0-SNAPSHOT, cassandra-6.0-alpha2,
Review Comment:
Since version pattern is changing can you please add tests for
"major.minor-SNAPSHOT" with no alpha/rc tag " versions?
##########
cassandra-six-zero-bridge/src/main/java/org/apache/cassandra/spark/reader/SSTableCache.java:
##########
@@ -0,0 +1,240 @@
+/*
+ * 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.spark.reader;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.metadata.MetadataComponent;
+import org.apache.cassandra.io.sstable.metadata.MetadataType;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.spark.data.FileType;
+import org.apache.cassandra.spark.data.SSTable;
+import org.apache.cassandra.spark.utils.Pair;
+import org.apache.cassandra.spark.utils.ThrowableUtils;
+import org.apache.cassandra.utils.BloomFilter;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Basic cache to reduce wasteful requests on the DataLayer for cacheable
SSTable metadata,
+ * useful when running many Spark tasks on the same Spark worker
+ *
+ * <p>Cassandra 6.0 needs its own copy of this class, because a {@link
CompressionMetadata} of 6.0 holds a
+ * reference to a compression dictionary and must release it when this class
stops holding the metadata.
+ */
+@SuppressWarnings("UnstableApiUsage")
+public class SSTableCache
+{
+ private static final Logger LOGGER =
LoggerFactory.getLogger(SSTableCache.class);
+
+ public static final SSTableCache INSTANCE = new SSTableCache();
+ private final Cache<SSTable, SummaryDbUtils.Summary> summary =
buildCache(propOrDefault("sbr.cache.summary.maxEntries", 4096),
+
propOrDefault("sbr.cache.summary.expireAfterMins", 15));
+ private final Cache<SSTable, Pair<DecoratedKey, DecoratedKey>> index =
buildCache(propOrDefault("sbr.cache.index.maxEntries", 128),
+
propOrDefault("sbr.cache.index.expireAfterMins", 60));
+ private final Cache<SSTable, Map<MetadataType, MetadataComponent>> stats =
buildCache(propOrDefault("sbr.cache.stats.maxEntries", 16384),
+
propOrDefault("sbr.cache.stats.expireAfterMins", 60));
+ private final Cache<SSTable, BloomFilter> filter =
buildCache(propOrDefault("sbr.cache.filter.maxEntries", 16384),
+
propOrDefault("sbr.cache.filter.expireAfterMins", 60));
+ // if compression is disabled then the CompressionInfo.db file will not
exist
+ // therefore we can cache as Optional to a) avoid null errors in the cache
and b) record that the component does not exist
+ private final Cache<SSTable, Optional<CompressionMetadata>>
compressionMetadata = buildCompressionMetadataCache(
+ propOrDefault("sbr.cache.compressionInfo.maxEntries", 128),
+ propOrDefault("sbr.cache.compressionInfo.expireAfterMins", 15));
+
+ static int propOrDefault(String name, int defaultValue)
+ {
+ return propOrDefault(name, defaultValue, Integer::parseInt);
+ }
+
+ private static long propOrDefault(String name, long defaultValue)
+ {
+ return propOrDefault(name, defaultValue, Long::parseLong);
+ }
+
+ private static boolean propOrDefault(String name, boolean defaultValue)
+ {
+ return propOrDefault(name, defaultValue, Boolean::parseBoolean);
+ }
+
+ private static <T> T propOrDefault(String name, T defaultValue,
Function<String, T> parser)
+ {
+ String str = System.getProperty(name);
+ if (str != null)
+ {
+ try
+ {
+ return parser.apply(str);
+ }
+ catch (NumberFormatException exception)
+ {
+ LOGGER.error("NumberFormatException for prop {} ", name,
exception);
+ }
+ }
+ return defaultValue;
+ }
+
+ private <T> Cache<SSTable, T> buildCache(int size, int expireAfterMins)
+ {
+ return CacheBuilder.newBuilder()
+ .expireAfterAccess(expireAfterMins,
TimeUnit.MINUTES)
+ .maximumSize(size)
+ .build();
+ }
+
+ /**
+ * Cassandra 6.0 gives a {@link CompressionMetadata} a reference to a
compression dictionary, which owns native
+ * zstd tables. Release that reference here, so the tables go away once
every reader of the dictionary has also
+ * released its own reference.
+ */
+ private Cache<SSTable, Optional<CompressionMetadata>>
buildCompressionMetadataCache(int size, int expireAfterMins)
+ {
+ return CacheBuilder.newBuilder()
+ .expireAfterAccess(expireAfterMins,
TimeUnit.MINUTES)
+ .maximumSize(size)
+ .<SSTable,
Optional<CompressionMetadata>>removalListener(notification -> {
+ Optional<CompressionMetadata> metadata =
notification.getValue();
+ if (metadata != null)
+ {
+
metadata.ifPresent(CompressionMetadata::close);
+ }
+ })
Review Comment:
nit: needs a test, can you force an entry out of this cache and verify the
dictionary ref actually got released.
##########
cassandra-four-zero-bridge/src/main/java/org/apache/cassandra/db/commitlog/BufferingCommitLogReader.java:
##########
@@ -553,19 +553,21 @@ private void readMutationInternal(byte[] inputBuffer,
messagingVersion,
DeserializationHelper.Flag.LOCAL);
}
- catch (UnknownTableException ex)
+ catch (Throwable t)
Review Comment:
Thanks for fixing this, I saw an issue with this earlier.
##########
cassandra-six-zero-bridge/src/main/java/org/apache/cassandra/io/sstable/format/bti/BtiReaderUtils.java:
##########
Review Comment:
can you please add tests for this class? there are tests for this 5.0 class,
may be you can copy them for 6.0 class
##########
cassandra-six-zero-bridge/src/main/java/org/apache/cassandra/spark/reader/SSTableReader.java:
##########
@@ -0,0 +1,987 @@
+/*
+ * 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.spark.reader;
+
+import java.io.DataInputStream;
+import java.io.EOFException;
+import java.io.IOError;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Suppliers;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Streams;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.config.DatabaseDescriptor;
+import org.apache.cassandra.cql3.ColumnIdentifier;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.DeletionTime;
+import org.apache.cassandra.db.RegularAndStaticColumns;
+import org.apache.cassandra.db.SerializationHeader;
+import org.apache.cassandra.db.UnfilteredDeserializer;
+import org.apache.cassandra.db.compression.CompressionDictionary;
+import org.apache.cassandra.db.filter.ColumnFilter;
+import org.apache.cassandra.db.marshal.AbstractType;
+import org.apache.cassandra.db.marshal.UTF8Type;
+import org.apache.cassandra.db.rows.DeserializationHelper;
+import org.apache.cassandra.db.rows.EncodingStats;
+import org.apache.cassandra.db.rows.Row;
+import org.apache.cassandra.db.rows.Unfiltered;
+import org.apache.cassandra.db.rows.UnfilteredRowIterator;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.ISSTableScanner;
+import org.apache.cassandra.io.sstable.SSTableSimpleIterator;
+import org.apache.cassandra.io.sstable.format.SSTableFormat;
+import org.apache.cassandra.io.sstable.format.Version;
+import org.apache.cassandra.io.sstable.format.bti.BtiReaderUtils;
+import org.apache.cassandra.io.sstable.indexsummary.IndexSummary;
+import org.apache.cassandra.io.sstable.metadata.MetadataComponent;
+import org.apache.cassandra.io.sstable.metadata.MetadataType;
+import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
+import org.apache.cassandra.io.sstable.metadata.ValidationMetadata;
+import org.apache.cassandra.io.util.DataInputPlus;
+import org.apache.cassandra.io.util.DataInputStreamPlus;
+import org.apache.cassandra.schema.ColumnMetadata;
+import org.apache.cassandra.schema.DroppedColumn;
+import org.apache.cassandra.schema.TableMetadata;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.spark.data.SSTable;
+import org.apache.cassandra.analytics.reader.common.RawInputStream;
+import org.apache.cassandra.spark.reader.common.SSTableStreamException;
+import org.apache.cassandra.spark.sparksql.filters.PartitionKeyFilter;
+import org.apache.cassandra.spark.sparksql.filters.PruneColumnFilter;
+import org.apache.cassandra.spark.sparksql.filters.SparkRangeFilter;
+import org.apache.cassandra.analytics.stats.Stats;
+import org.apache.cassandra.spark.sparksql.filters.SSTableTimeRangeFilter;
+import org.apache.cassandra.spark.utils.ByteBufferUtils;
+import org.apache.cassandra.spark.utils.Pair;
+import org.apache.cassandra.spark.utils.ThrowableUtils;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.concurrent.Ref;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+@SuppressWarnings("unused")
+public class SSTableReader implements SparkSSTableReader, Scannable
+{
+ private static final Logger LOGGER =
LoggerFactory.getLogger(SSTableReader.class);
+
+ private final TableMetadata metadata;
+ @NotNull
+ private final SSTable ssTable;
+ private final StatsMetadata statsMetadata;
+ @NotNull
+ private final Version version;
+ @NotNull
+ private final DecoratedKey first;
+ @NotNull
+ private final DecoratedKey last;
+ @NotNull
+ private final BigInteger firstToken;
+ @NotNull
+ private final BigInteger lastToken;
+ private final SerializationHeader header;
+ private final DeserializationHelper helper;
+ @NotNull
+ private final AtomicReference<SSTableStreamReader> reader = new
AtomicReference<>(null);
+ @Nullable
+ private final SparkRangeFilter sparkRangeFilter;
+ @NotNull
+ private final List<PartitionKeyFilter> partitionKeyFilters;
+ @NotNull
+ private final SSTableTimeRangeFilter sstableTimeRangeFilter;
+ @NotNull
+ private final Stats stats;
+ @Nullable
+ private Long startOffset = null;
+ private Long openedNanos = null;
+ @NotNull
+ private final Function<StatsMetadata, Boolean> isRepaired;
+
+ public static class Builder
+ {
+ @NotNull
+ final TableMetadata metadata;
+ @NotNull
+ final SSTable ssTable;
+ @Nullable
+ PruneColumnFilter columnFilter = null;
+ boolean readIndexOffset = true;
+ @NotNull
+ Stats stats = Stats.DoNothingStats.INSTANCE;
+ boolean useIncrementalRepair = true;
+ boolean isRepairPrimary = false;
+ Function<StatsMetadata, Boolean> isRepaired = stats ->
stats.repairedAt != ActiveRepairService.UNREPAIRED_SSTABLE;
+ @Nullable
+ SparkRangeFilter sparkRangeFilter = null;
+ @NotNull
+ final List<PartitionKeyFilter> partitionKeyFilters = new ArrayList<>();
+ @NotNull
+ SSTableTimeRangeFilter sstableTimeRangeFilter =
SSTableTimeRangeFilter.ALL;
+
+ Builder(@NotNull TableMetadata metadata, @NotNull SSTable ssTable)
+ {
+ this.metadata = metadata;
+ this.ssTable = ssTable;
+ }
+
+ public Builder withSparkRangeFilter(@Nullable SparkRangeFilter
sparkRangeFilter)
+ {
+ this.sparkRangeFilter = sparkRangeFilter;
+ return this;
+ }
+
+ public Builder withPartitionKeyFilters(@Nullable
Collection<PartitionKeyFilter> partitionKeyFilters)
+ {
+ if (partitionKeyFilters != null)
+ {
+ this.partitionKeyFilters.addAll(partitionKeyFilters);
+ }
+ return this;
+ }
+
+ public Builder withPartitionKeyFilter(@NotNull PartitionKeyFilter
partitionKeyFilter)
+ {
+ partitionKeyFilters.add(partitionKeyFilter);
+ return this;
+ }
+
+ public Builder withTimeRangeFilter(@Nullable SSTableTimeRangeFilter
sstableTimeRangeFilter)
+ {
+ if (sstableTimeRangeFilter != null)
+ {
+ this.sstableTimeRangeFilter = sstableTimeRangeFilter;
+ }
+ return this;
+ }
+
+ public Builder withColumnFilter(@Nullable PruneColumnFilter
columnFilter)
+ {
+ this.columnFilter = columnFilter;
+ return this;
+ }
+
+ public Builder withReadIndexOffset(boolean readIndexOffset)
+ {
+ this.readIndexOffset = readIndexOffset;
+ return this;
+ }
+
+ public Builder withStats(@NotNull Stats stats)
+ {
+ this.stats = stats;
+ return this;
+ }
+
+ public Builder useIncrementalRepair(boolean useIncrementalRepair)
+ {
+ this.useIncrementalRepair = useIncrementalRepair;
+ return this;
+ }
+
+ public Builder isRepairPrimary(boolean isRepairPrimary)
+ {
+ this.isRepairPrimary = isRepairPrimary;
+ return this;
+ }
+
+ public Builder withIsRepairedFunction(Function<StatsMetadata, Boolean>
isRepaired)
+ {
+ this.isRepaired = isRepaired;
+ return this;
+ }
+
+ public SSTableReader build() throws IOException
+ {
+ return new SSTableReader(metadata,
+ ssTable,
+ sparkRangeFilter,
+ partitionKeyFilters,
+ sstableTimeRangeFilter,
+ columnFilter,
+ readIndexOffset,
+ stats,
+ useIncrementalRepair,
+ isRepairPrimary,
+ isRepaired);
+ }
+ }
+
+ public static Builder builder(@NotNull TableMetadata metadata, @NotNull
SSTable ssTable)
+ {
+ return new Builder(metadata, ssTable);
+ }
+
+ // CHECKSTYLE IGNORE: Constructor with many parameters
+ public SSTableReader(@NotNull TableMetadata metadata,
+ @NotNull SSTable ssTable,
+ @Nullable SparkRangeFilter sparkRangeFilter,
+ @NotNull List<PartitionKeyFilter> partitionKeyFilters,
+ @NotNull SSTableTimeRangeFilter
sstableTimeRangeFilter,
+ @Nullable PruneColumnFilter columnFilter,
+ boolean readIndexOffset,
+ @NotNull Stats stats,
+ boolean useIncrementalRepair,
+ boolean isRepairPrimary,
+ @NotNull Function<StatsMetadata, Boolean> isRepaired)
throws IOException
+ {
+ long startTimeNanos = System.nanoTime();
+ long now;
+ this.ssTable = ssTable;
+ this.stats = stats;
+ this.isRepaired = isRepaired;
+ this.sparkRangeFilter = sparkRangeFilter;
+
+ Descriptor descriptor =
ReaderUtils.constructDescriptor(metadata.keyspace, metadata.name, ssTable);
+ this.version = descriptor.version;
+
+ SummaryDbUtils.Summary summary = null;
+ Pair<DecoratedKey, DecoratedKey> keys = null;
+ try
+ {
+ now = System.nanoTime();
+ if (ssTable.isBigFormat())
+ {
+ summary = SSTableCache.INSTANCE.keysFromSummary(metadata,
ssTable);
+ stats.readSummaryDb(ssTable, System.nanoTime() - now);
+ keys = Pair.of(summary.first(), summary.last());
+ }
+ }
+ catch (IOException exception)
+ {
+ LOGGER.warn("Failed to read Summary.db file ssTable='{}'",
ssTable, exception);
+ }
+
+ if (keys == null)
+ {
+ if (ssTable.isBigFormat())
+ {
+ LOGGER.warn("Could not load first and last key from Summary.db
file, so attempting Index.db fileName={}",
+ ssTable.getDataFileName());
+ }
+ now = System.nanoTime();
+ keys = SSTableCache.INSTANCE.keysFromIndex(metadata, ssTable);
+ stats.readIndexDb(ssTable, System.nanoTime() - now);
+ }
+
+ if (keys == null)
+ {
+ throw new IOException("Could not load SSTable first or last
tokens");
+ }
+
+ this.first = keys.left;
+ this.last = keys.right;
+ this.firstToken = ReaderUtils.tokenToBigInteger(first.getToken());
+ this.lastToken = ReaderUtils.tokenToBigInteger(last.getToken());
+ TokenRange readerRange = range();
+
+ List<PartitionKeyFilter> matchingKeyFilters =
partitionKeyFilters.stream()
+ .filter(filter -> readerRange.contains(filter.token()))
+ .collect(Collectors.toList());
+ boolean overlapsSparkRange = sparkRangeFilter == null ||
SparkSSTableReader.overlaps(this, sparkRangeFilter.tokenRange());
+ if (!overlapsSparkRange // SSTable doesn't overlap with Spark worker
token range
+ || (matchingKeyFilters.isEmpty() &&
!partitionKeyFilters.isEmpty())) // No matching partition key filters overlap
with SSTable
+ {
+ this.partitionKeyFilters = Collections.emptyList();
+ stats.skippedSSTable(sparkRangeFilter, partitionKeyFilters,
firstToken, lastToken);
+ LOGGER.info("Ignoring SSTableReader with firstToken={}
lastToken={}, does not overlap with any filter",
+ firstToken, lastToken);
+ statsMetadata = null;
+ header = null;
+ helper = null;
+ this.metadata = null;
+ this.sstableTimeRangeFilter = SSTableTimeRangeFilter.ALL;
+ return;
+ }
+
+ if (!matchingKeyFilters.isEmpty())
+ {
+ List<PartitionKeyFilter> matchInBloomFilter =
+ ReaderUtils.filterKeyInBloomFilter(ssTable,
metadata.partitioner, descriptor, matchingKeyFilters);
+ this.partitionKeyFilters =
ImmutableList.copyOf(matchInBloomFilter);
+
+ // Check if required keys are actually present
+ if (matchInBloomFilter.isEmpty() ||
!ReaderUtils.anyFilterKeyInIndex(ssTable, metadata, descriptor,
matchInBloomFilter))
+ {
+ if (matchInBloomFilter.isEmpty())
+ {
+ stats.missingInBloomFilter();
+ }
+ else
+ {
+ stats.missingInIndex();
+ }
+ LOGGER.info("Ignoring SSTable {}, no match found in index file
for key filters",
+ this.ssTable.getDataFileName());
+ statsMetadata = null;
+ header = null;
+ helper = null;
+ this.metadata = null;
+ this.sstableTimeRangeFilter = SSTableTimeRangeFilter.ALL;
+ return;
+ }
+ }
+ else
+ {
+ this.partitionKeyFilters =
ImmutableList.copyOf(partitionKeyFilters);
+ }
+
+ Map<MetadataType, MetadataComponent> componentMap =
SSTableCache.INSTANCE.componentMapFromStats(ssTable, descriptor);
+
+ ValidationMetadata validation = (ValidationMetadata)
componentMap.get(MetadataType.VALIDATION);
+ if (validation != null &&
!validation.partitioner.equals(metadata.partitioner.getClass().getName()))
+ {
+ throw new IllegalStateException("Partitioner in ValidationMetadata
does not match TableMetaData: "
+ + validation.partitioner + " vs. " +
metadata.partitioner.getClass().getName());
+ }
+
+ this.statsMetadata = (StatsMetadata)
componentMap.get(MetadataType.STATS);
+ if (!sstableTimeRangeFilter.overlaps(statsMetadata.minTimestamp,
statsMetadata.maxTimestamp))
+ {
+ LOGGER.info("Ignoring SSTableReader with minTimestamp={}
maxTimestamp={}, does not overlap with filter {}",
+ this.statsMetadata.minTimestamp,
this.statsMetadata.maxTimestamp, sstableTimeRangeFilter);
+ header = null;
+ helper = null;
+ this.metadata = null;
+ this.sstableTimeRangeFilter = SSTableTimeRangeFilter.ALL;
+ return;
+ }
+ else
+ {
+ this.sstableTimeRangeFilter = sstableTimeRangeFilter;
+ }
+
+ SerializationHeader.Component headerComp =
(SerializationHeader.Component) componentMap.get(MetadataType.HEADER);
+ if (headerComp == null)
+ {
+ throw new IOException("Cannot read SSTable if cannot deserialize
stats header info");
+ }
+
+ if (useIncrementalRepair && !isRepairPrimary && isRepaired())
+ {
+ stats.skippedRepairedSSTable(ssTable, statsMetadata.repairedAt);
+ LOGGER.info("Ignoring repaired SSTable on non-primary repair
replica ssTable='{}' repairedAt={}",
+ ssTable, statsMetadata.repairedAt);
+ header = null;
+ helper = null;
+ this.metadata = null;
+ return;
+ }
+
+ Set<String> columnNames = Streams.concat(metadata.columns().stream(),
+
metadata.staticColumns().stream())
+ .map(column -> column.name.toString())
+ .collect(Collectors.toSet());
+ // Cassandra 6.0 gives every column a uniqueId, and
TableMetadata.Builder assigns one only when no column
+ // already has one, so a dropped column added here must carry an
explicit id. Seed the map with the
+ // table's own dropped columns, so that the ids they hold stay
accounted for.
+ Map<ByteBuffer, DroppedColumn> droppedColumns = new
HashMap<>(metadata.droppedColumns);
+ int knownDroppedColumns = droppedColumns.size();
+ // Almost every SSTable adds no dropped column, so pay for the id scan
only when one does
+ TableMetadata schemaMetadata = metadata;
+ Supplier<AtomicInteger> nextUniqueId = Suppliers.memoize(() -> new
AtomicInteger(nextUniqueId(schemaMetadata)));
+ addDroppedColumns(droppedColumns,
+ nextUniqueId,
+ metadata.keyspace,
+ metadata.name,
+ ssTable,
+ headerComp.getRegularColumns(),
+ columnNames,
+ ColumnMetadata.Kind.REGULAR);
+ addDroppedColumns(droppedColumns,
+ nextUniqueId,
+ metadata.keyspace,
+ metadata.name,
+ ssTable,
+ headerComp.getStaticColumns(),
+ columnNames,
+ ColumnMetadata.Kind.STATIC);
+ if (droppedColumns.size() > knownDroppedColumns)
+ {
+ LOGGER.info("Rebuilding table metadata with dropped columns
numDroppedColumns={} ssTable='{}'",
+ droppedColumns.size(), ssTable);
+ metadata =
metadata.unbuild().droppedColumns(droppedColumns).build();
+ }
+
+ this.header = headerComp.toHeader(metadata);
+ this.helper = new DeserializationHelper(metadata,
+
getSSTableVersion(ssTable).correspondingMessagingVersion(),
+
DeserializationHelper.Flag.FROM_REMOTE,
+ buildColumnFilter(metadata,
columnFilter));
+ this.metadata = metadata;
+
+ if (readIndexOffset)
+ {
+ if (summary != null)
+ {
+ // BIG format
+ SummaryDbUtils.Summary finalSummary = summary;
+ extractRange(sparkRangeFilter, partitionKeyFilters)
+ .ifPresent(range ->
readOffsets(finalSummary.summary(), range));
+ }
+ else
+ {
+ // BTI format
+ extractRange(sparkRangeFilter, partitionKeyFilters)
+ .ifPresent(range -> {
+ startOffset =
BtiReaderUtils.startOffsetInDataFile(ssTable,
+
this.metadata,
+
descriptor,
+
range);
+ });
+ }
+ }
+ else
+ {
+ LOGGER.warn("Reading SSTable without looking up start/end offset,
performance will potentially be degraded");
+ }
+
+ // Open SSTableStreamReader so opened in parallel inside thread pool
+ // and buffered + ready to go when CompactionIterator starts reading
+ reader.set(new SSTableStreamReader());
+ stats.openedSSTable(ssTable, System.nanoTime() - startTimeNanos);
+ this.openedNanos = System.nanoTime();
+ }
+
+ /**
+ * Return the first column uniqueId that no column of the table uses,
continuing the single sequence that
+ * Cassandra 6.0 numbers the live and the dropped columns in
+ */
+ private static int nextUniqueId(TableMetadata metadata)
+ {
+ int highest = ColumnMetadata.NO_UNIQUE_ID;
+ // columns() covers the partition key, clustering, regular and static
columns
+ for (ColumnMetadata column : metadata.columns())
+ {
+ highest = Math.max(highest, column.uniqueId);
+ }
+ for (DroppedColumn dropped : metadata.droppedColumns.values())
+ {
+ highest = Math.max(highest, dropped.column.uniqueId);
+ }
+ int nextId = Math.max(0, highest + 1);
+ // TableMetadata sizes its by-id column array at one slot per
addressable column and indexes it by
+ // uniqueId, so the ids must run 0..size-1 for each id assigned from
here to land inside the array
+ int addressableColumns =
metadata.regularAndStaticAndDroppedColumns().size()
+ + metadata.partitionKeyColumns().size()
+ + metadata.clusteringColumns().size();
+ Preconditions.checkState(nextId <= addressableColumns,
+ "Column uniqueIds of %s.%s exceed the by-id
array: nextId=%s columns=%s",
+ metadata.keyspace, metadata.name, nextId,
addressableColumns);
+ return nextId;
+ }
+
+ /**
+ * Add one dropped column for every column of the SSTable that the table
schema does not hold, taking each
+ * uniqueId from {@code nextUniqueId}
+ */
+ private static void addDroppedColumns(Map<ByteBuffer, DroppedColumn>
droppedColumns,
+ Supplier<AtomicInteger> nextUniqueId,
+ String keyspace,
+ String table,
+ SSTable ssTable,
+ Map<ByteBuffer, AbstractType<?>>
columns,
+ Set<String> columnNames,
+ ColumnMetadata.Kind kind)
+ {
+ for (Map.Entry<ByteBuffer, AbstractType<?>> entry : columns.entrySet())
+ {
+ String colName = UTF8Type.instance.getString((entry.getKey()));
+ if (!columnNames.contains(colName) &&
!droppedColumns.containsKey(entry.getKey()))
+ {
+ AbstractType<?> type = entry.getValue();
+ LOGGER.warn("Dropped column found colName={} sstable='{}'",
colName, ssTable);
+ ColumnMetadata column = new ColumnMetadata(keyspace,
+ table,
+
ColumnIdentifier.getInterned(colName, true),
+ type,
+
nextUniqueId.get().getAndIncrement(),
+
ColumnMetadata.NO_POSITION,
+ kind,
+ null); // TODO:
Honor server-side column masking.
+ long droppedTime =
TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis())
+ - TimeUnit.MINUTES.toMicros(60);
+ droppedColumns.put(entry.getKey(), new DroppedColumn(column,
droppedTime));
+ }
+ }
+ }
+
+ /**
+ * Merge all the partition key filters to give the token range we care
about.
+ * If no partition key filters, then use the Spark worker token range.
+ *
+ * @param sparkRangeFilter optional spark range filter
+ * @param partitionKeyFilters list of partition key filters
+ * @return the token range we care about for this Spark worker
+ */
+ public static Optional<TokenRange> extractRange(@Nullable SparkRangeFilter
sparkRangeFilter,
+ @NotNull
List<PartitionKeyFilter> partitionKeyFilters)
+ {
+ Optional<TokenRange> partitionKeyRange = partitionKeyFilters.stream()
+
.map(PartitionKeyFilter::tokenRange)
+
.reduce(TokenRange::merge);
+ return partitionKeyRange.isPresent()
+ ? partitionKeyRange
+ : Optional.ofNullable(sparkRangeFilter != null ?
sparkRangeFilter.tokenRange() : null);
+ }
+
+ /**
+ * Read Data.db offsets by binary searching Summary.db into Index.db, then
reading offsets in Index.db
+ *
+ * @param indexSummary Summary.db index summary
+ * @param range token range we care about for this Spark worker
+ */
+ private void readOffsets(IndexSummary indexSummary, TokenRange range)
+ {
+ try
+ {
+ // If start is null we failed to find an overlapping token in the
Index.db file,
+ // this is unlikely as we already pre-filter the SSTable based on
the start-end token range.
+ // But in this situation we read the entire Data.db file to be
safe, even if it hits performance.
+ startOffset = IndexDbUtils.findDataDbOffset(indexSummary, range,
metadata.partitioner, ssTable, stats);
+ if (startOffset == null)
+ {
+ LOGGER.error("Failed to find Data.db start offset, performance
will be degraded sstable='{}'", ssTable);
+ }
+ }
+ catch (IOException exception)
+ {
+ LOGGER.warn("IOException finding SSTable offsets, cannot skip
directly to start offset in Data.db. "
+ + "Performance will be degraded.", exception);
+ }
+ }
+
+ /**
+ * Build a ColumnFilter if we need to prune any columns for more efficient
deserialization of the SSTable
+ *
+ * @param metadata TableMetadata object
+ * @param columnFilter prune column filter
+ * @return ColumnFilter if and only if we can prune any columns when
deserializing the SSTable,
+ * otherwise return null
+ */
+ @Nullable
+ private static ColumnFilter buildColumnFilter(TableMetadata metadata,
@Nullable PruneColumnFilter columnFilter)
+ {
+ if (columnFilter == null)
+ {
+ return null;
+ }
+ List<ColumnMetadata> include = metadata.columns().stream()
+ .filter(column ->
columnFilter.includeColumn(column.name.toString()))
+ .collect(Collectors.toList());
+ if (include.size() == metadata.columns().size())
+ {
+ return null; // No columns pruned
+ }
+ return ColumnFilter.allRegularColumnsBuilder(metadata, false)
+ .addAll(include)
+ .build();
+ }
+
+ public SSTable sstable()
+ {
+ return ssTable;
+ }
+
+ public boolean ignore()
+ {
+ return reader.get() == null;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(metadata.keyspace, metadata.name, ssTable);
+ }
+
+ @Override
+ public boolean equals(Object other)
+ {
+ return other instanceof SSTableReader
+ && this.metadata.keyspace.equals(((SSTableReader)
other).metadata.keyspace)
+ && this.metadata.name.equals(((SSTableReader) other).metadata.name)
+ && this.ssTable.equals(((SSTableReader) other).ssTable);
+ }
+
+ public boolean isRepaired()
+ {
+ return isRepaired.apply(statsMetadata);
+ }
+
+ public DecoratedKey first()
+ {
+ return first;
+ }
+
+ public DecoratedKey last()
+ {
+ return last;
+ }
+
+ public long getMinTimestamp()
+ {
+ return statsMetadata.minTimestamp;
+ }
+
+ public long getMaxTimestamp()
+ {
+ return statsMetadata.maxTimestamp;
+ }
+
+ public StatsMetadata getSSTableMetadata()
+ {
+ return statsMetadata;
+ }
+
+ @Override
+ public ISSTableScanner scanner()
+ {
+ ISSTableScanner result = reader.getAndSet(null);
+ if (result == null)
+ {
+ throw new IllegalStateException("SSTableStreamReader cannot be
re-used");
+ }
+ return result;
+ }
+
+ @Override
+ @NotNull
+ public BigInteger firstToken()
+ {
+ return firstToken;
+ }
+
+ @Override
+ @NotNull
+ public BigInteger lastToken()
+ {
+ return lastToken;
+ }
+
+ public class SSTableStreamReader implements ISSTableScanner
+ {
+ private final DataInputStream dis;
+ private final DataInputPlus in;
+ final RawInputStream dataStream;
+ private DecoratedKey key;
+ private DeletionTime partitionLevelDeletion;
+ private SSTableSimpleIterator iterator;
+ private Row staticRow;
+ @Nullable
+ private final BigInteger lastToken;
+ // Cassandra 6.0 decompresses through native zstd tables that a
compression dictionary owns. Hold a
+ // reference for the life of this scanner, so a removal from
SSTableCache cannot free them mid-read
+ @Nullable
+ private final Ref<? extends CompressionDictionary> dictionaryRef;
+ private long lastTimeNanos = System.nanoTime();
+
+ SSTableStreamReader() throws IOException
+ {
+ lastToken = sparkRangeFilter != null ?
sparkRangeFilter.tokenRange().upperEndpoint() : null;
+ @Nullable CompressionMetadata compressionMetadata =
SSTableCache.INSTANCE.compressionMetadata(ssTable,
+
version.hasMaxCompressedLength(),
+
metadata.params.crcCheckChance);
+ dictionaryRef = compressionMetadata != null ?
compressionMetadata.acquireDictionaryRef() : null;
Review Comment:
dictionaryRef is acquired here, but openDataStream(),
CompressedRawInputStream.from(...), and skipFully(...) can still throw after
the reference is acquired, leaking it since no one calls close() on a
constructor that never returned.
Since dictionaryRef is only used later in close(), can we move its
acquisition to the end of the constructor, after everything that can throw has
already succeeded?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]