You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by dc...@apache.org on 2023/03/15 23:22:35 UTC
[cassandra] branch trunk updated (a76286795f -> 92c90cd4ef)
This is an automated email from the ASF dual-hosted git repository.
dcapwell pushed a change to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra.git
from a76286795f Add system_views.max_sstable_size and system_views.max_sstable_duration tables
new d5b1483703 Incompatible file system thrown while running Simulator
new 92c90cd4ef Merge branch 'cassandra-4.1' into trunk
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
checkstyle.xml | 2 +-
.../apache/cassandra/audit/AuditLogOptions.java | 4 ++--
.../org/apache/cassandra/audit/BinAuditLogger.java | 4 ++--
.../cassandra/config/DatabaseDescriptor.java | 11 +++++------
.../cassandra/hadoop/cql3/CqlConfigHelper.java | 6 +++---
.../io/sstable/format/SortedTableScrubber.java | 3 +--
src/java/org/apache/cassandra/io/util/File.java | 12 +++++++----
.../security/FileBasedSslContextFactory.java | 5 ++---
.../apache/cassandra/security/JKSKeyProvider.java | 4 ++--
.../security/PEMBasedSslContextFactory.java | 3 +--
.../apache/cassandra/service/CassandraDaemon.java | 5 ++---
.../service/FileSystemOwnershipCheck.java | 3 +--
.../apache/cassandra/service/StartupChecks.java | 7 +++----
.../apache/cassandra/service/StorageService.java | 3 +--
.../cassandra/service/snapshot/SnapshotLoader.java | 3 +--
.../cassandra/service/snapshot/TableSnapshot.java | 3 +--
.../org/apache/cassandra/tools/HashPassword.java | 5 +++--
.../cassandra/tools/SSTableRepairedAtSetter.java | 3 +--
src/java/org/apache/cassandra/utils/HeapUtils.java | 3 +--
.../{OrderedOn.java => SimulationException.java} | 23 +++++++++++++---------
.../cassandra/simulator/SimulationRunner.java | 7 ++++++-
21 files changed, 61 insertions(+), 58 deletions(-)
copy test/simulator/main/org/apache/cassandra/simulator/{OrderedOn.java => SimulationException.java} (63%)
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org
[cassandra] 01/01: Merge branch 'cassandra-4.1' into trunk
Posted by dc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
dcapwell pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra.git
commit 92c90cd4ef385cab0bd7acfbd9a10261110f85ee
Merge: a76286795f d5b1483703
Author: David Capwell <dc...@apache.org>
AuthorDate: Wed Mar 15 16:19:05 2023 -0700
Merge branch 'cassandra-4.1' into trunk
checkstyle.xml | 2 +-
.../apache/cassandra/audit/AuditLogOptions.java | 4 +--
.../org/apache/cassandra/audit/BinAuditLogger.java | 4 +--
.../cassandra/config/DatabaseDescriptor.java | 11 +++----
.../cassandra/hadoop/cql3/CqlConfigHelper.java | 6 ++--
.../io/sstable/format/SortedTableScrubber.java | 3 +-
src/java/org/apache/cassandra/io/util/File.java | 12 ++++---
.../security/FileBasedSslContextFactory.java | 5 ++-
.../apache/cassandra/security/JKSKeyProvider.java | 4 +--
.../security/PEMBasedSslContextFactory.java | 3 +-
.../apache/cassandra/service/CassandraDaemon.java | 5 ++-
.../service/FileSystemOwnershipCheck.java | 3 +-
.../apache/cassandra/service/StartupChecks.java | 7 ++--
.../apache/cassandra/service/StorageService.java | 3 +-
.../cassandra/service/snapshot/SnapshotLoader.java | 3 +-
.../cassandra/service/snapshot/TableSnapshot.java | 3 +-
.../org/apache/cassandra/tools/HashPassword.java | 5 +--
.../cassandra/tools/SSTableRepairedAtSetter.java | 3 +-
src/java/org/apache/cassandra/utils/HeapUtils.java | 3 +-
.../cassandra/simulator/SimulationException.java | 37 ++++++++++++++++++++++
.../cassandra/simulator/SimulationRunner.java | 7 +++-
21 files changed, 84 insertions(+), 49 deletions(-)
diff --cc src/java/org/apache/cassandra/config/DatabaseDescriptor.java
index e314f0a677,d2c529c3d4..46b16db90c
--- a/src/java/org/apache/cassandra/config/DatabaseDescriptor.java
+++ b/src/java/org/apache/cassandra/config/DatabaseDescriptor.java
@@@ -27,8 -25,6 +27,7 @@@ import java.net.NetworkInterface
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.file.FileStore;
+import java.nio.file.Path;
- import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
@@@ -4585,96 -4398,4 +4584,96 @@@ public class DatabaseDescripto
{
conf.min_tracked_partition_tombstone_count = value;
}
+
+ public static boolean getDumpHeapOnUncaughtException()
+ {
+ return conf.dump_heap_on_uncaught_exception;
+ }
+
+ /**
+ * @return Whether the path exists (be it created now or already prior)
+ */
+ private static boolean maybeCreateHeapDumpPath()
+ {
+ if (!conf.dump_heap_on_uncaught_exception)
+ return false;
+
+ Path heap_dump_path = getHeapDumpPath();
+ if (heap_dump_path == null)
+ {
+ logger.warn("Neither -XX:HeapDumpPath nor cassandra.yaml:heap_dump_path are set; unable to create a directory to hold the output.");
+ return false;
+ }
- if (PathUtils.exists(Paths.get(conf.heap_dump_path)))
++ if (PathUtils.exists(File.getPath(conf.heap_dump_path)))
+ return true;
- return PathUtils.createDirectoryIfNotExists(Paths.get(conf.heap_dump_path));
++ return PathUtils.createDirectoryIfNotExists(File.getPath(conf.heap_dump_path));
+ }
+
+ /**
+ * As this is at its heart a debug operation (getting a one-shot heapdump from an uncaught exception), we support
+ * both the more evolved cassandra.yaml approach but also the -XX param to override it on a one-off basis so you don't
+ * have to change the full config of a node or a cluster in order to get a heap dump from a single node that's
+ * misbehaving.
+ * @return the absolute path of the -XX param if provided, else the heap_dump_path in cassandra.yaml
+ */
+ public static Path getHeapDumpPath()
+ {
+ RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
+ Optional<String> pathArg = runtimeMxBean.getInputArguments().stream().filter(s -> s.startsWith("-XX:HeapDumpPath=")).findFirst();
+
+ if (pathArg.isPresent())
+ {
+ Pattern HEAP_DUMP_PATH_SPLITTER = Pattern.compile("HeapDumpPath=");
+ String fullHeapPathString = HEAP_DUMP_PATH_SPLITTER.split(pathArg.get())[1];
- Path absolutePath = Paths.get(fullHeapPathString).toAbsolutePath();
++ Path absolutePath = File.getPath(fullHeapPathString).toAbsolutePath();
+ Path basePath = fullHeapPathString.endsWith(".hprof") ? absolutePath.subpath(0, absolutePath.getNameCount() - 1) : absolutePath;
- return Paths.get("/").resolve(basePath);
++ return File.getPath("/").resolve(basePath);
+ }
+ if (conf.heap_dump_path == null)
+ throw new ConfigurationException("Attempted to get heap dump path without -XX:HeapDumpPath or cassandra.yaml:heap_dump_path set.");
- return Paths.get(conf.heap_dump_path);
++ return File.getPath(conf.heap_dump_path);
+ }
+
+ public static void setDumpHeapOnUncaughtException(boolean enabled)
+ {
+ conf.dump_heap_on_uncaught_exception = enabled;
+ boolean pathExists = maybeCreateHeapDumpPath();
+
+ if (enabled && !pathExists)
+ {
+ logger.error("Attempted to enable heap dump but cannot create the requested path. Disabling.");
+ conf.dump_heap_on_uncaught_exception = false;
+ }
+ else
+ logger.info("Setting dump_heap_on_uncaught_exception to {}", enabled);
+ }
+
+ public static boolean getSStableReadRatePersistenceEnabled()
+ {
+ return conf.sstable_read_rate_persistence_enabled;
+ }
+
+ public static void setSStableReadRatePersistenceEnabled(boolean enabled)
+ {
+ if (enabled != conf.sstable_read_rate_persistence_enabled)
+ {
+ logger.info("Setting sstable_read_rate_persistence_enabled to {}", enabled);
+ conf.sstable_read_rate_persistence_enabled = enabled;
+ }
+ }
+
+ public static boolean getClientRequestSizeMetricsEnabled()
+ {
+ return conf.client_request_size_metrics_enabled;
+ }
+
+ public static void setClientRequestSizeMetricsEnabled(boolean enabled)
+ {
+ conf.client_request_size_metrics_enabled = enabled;
+ }
+
+ public static Map<String, Supplier<SSTableFormat<?, ?>>> getSSTableFormatFactories()
+ {
+ return Objects.requireNonNull(sstableFormatFactories, "Forgot to initialize DatabaseDescriptor?");
+ }
}
diff --cc src/java/org/apache/cassandra/io/sstable/format/SortedTableScrubber.java
index 07255873e6,0000000000..95c913acce
mode 100644,000000..100644
--- a/src/java/org/apache/cassandra/io/sstable/format/SortedTableScrubber.java
+++ b/src/java/org/apache/cassandra/io/sstable/format/SortedTableScrubber.java
@@@ -1,631 -1,0 +1,630 @@@
+/*
+ * 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.io.sstable.format;
+
+import java.io.IOError;
+import java.io.IOException;
- import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import javax.annotation.concurrent.NotThreadSafe;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.cassandra.db.ClusteringComparator;
+import org.apache.cassandra.db.ColumnFamilyStore;
+import org.apache.cassandra.db.DecoratedKey;
+import org.apache.cassandra.db.LivenessInfo;
+import org.apache.cassandra.db.compaction.CompactionInfo;
+import org.apache.cassandra.db.compaction.CompactionManager;
+import org.apache.cassandra.db.compaction.OperationType;
+import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
+import org.apache.cassandra.db.partitions.ImmutableBTreePartition;
+import org.apache.cassandra.db.partitions.Partition;
+import org.apache.cassandra.db.rows.AbstractCell;
+import org.apache.cassandra.db.rows.Cell;
+import org.apache.cassandra.db.rows.ColumnData;
+import org.apache.cassandra.db.rows.ComplexColumnData;
+import org.apache.cassandra.db.rows.Row;
+import org.apache.cassandra.db.rows.Rows;
+import org.apache.cassandra.db.rows.Unfiltered;
+import org.apache.cassandra.db.rows.UnfilteredRowIterator;
+import org.apache.cassandra.db.rows.UnfilteredRowIterators;
+import org.apache.cassandra.db.rows.WrappingUnfilteredRowIterator;
+import org.apache.cassandra.exceptions.ConfigurationException;
+import org.apache.cassandra.io.sstable.Component;
+import org.apache.cassandra.io.sstable.Descriptor;
+import org.apache.cassandra.io.sstable.IScrubber;
+import org.apache.cassandra.io.sstable.SSTableIdentityIterator;
+import org.apache.cassandra.io.sstable.SSTableRewriter;
+import org.apache.cassandra.io.sstable.format.SSTableFormat.Components;
+import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
+import org.apache.cassandra.io.util.File;
+import org.apache.cassandra.io.util.RandomAccessReader;
+import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.utils.AbstractIterator;
+import org.apache.cassandra.utils.ByteBufferUtil;
+import org.apache.cassandra.utils.FBUtilities;
+import org.apache.cassandra.utils.OutputHandler;
+import org.apache.cassandra.utils.TimeUUID;
+import org.apache.cassandra.utils.concurrent.Refs;
+import org.apache.cassandra.utils.memory.HeapCloner;
+
+import static org.apache.cassandra.utils.TimeUUID.Generator.nextTimeUUID;
+
+@NotThreadSafe
+public abstract class SortedTableScrubber<R extends SSTableReaderWithFilter> implements IScrubber
+{
+ private final static Logger logger = LoggerFactory.getLogger(SortedTableScrubber.class);
+
+ protected final ColumnFamilyStore cfs;
+ protected final LifecycleTransaction transaction;
+ protected final File destination;
+ protected final IScrubber.Options options;
+ protected final R sstable;
+ protected final OutputHandler outputHandler;
+ protected final boolean isCommutative;
+ protected final long expectedBloomFilterSize;
+ protected final ReadWriteLock fileAccessLock = new ReentrantReadWriteLock();
+ protected final RandomAccessReader dataFile;
+ protected final ScrubInfo scrubInfo;
+
+ protected final NegativeLocalDeletionInfoMetrics negativeLocalDeletionInfoMetrics = new NegativeLocalDeletionInfoMetrics();
+
+ private static final Comparator<Partition> partitionComparator = Comparator.comparing(Partition::partitionKey);
+ protected final SortedSet<Partition> outOfOrder = new TreeSet<>(partitionComparator);
+
+
+ protected int goodPartitions;
+ protected int badPartitions;
+ protected int emptyPartitions;
+
+
+ protected SortedTableScrubber(ColumnFamilyStore cfs,
+ LifecycleTransaction transaction,
+ OutputHandler outputHandler,
+ Options options)
+ {
+ this.sstable = (R) transaction.onlyOne();
+ Preconditions.checkNotNull(sstable.metadata());
+ assert sstable.metadata().keyspace.equals(cfs.keyspace.getName());
+ if (!sstable.descriptor.cfname.equals(cfs.metadata().name))
+ {
+ logger.warn("Descriptor points to a different table {} than metadata {}", sstable.descriptor.cfname, cfs.metadata().name);
+ }
+ try
+ {
+ sstable.metadata().validateCompatibility(cfs.metadata());
+ }
+ catch (ConfigurationException ex)
+ {
+ logger.warn("Descriptor points to a different table {} than metadata {}", sstable.descriptor.cfname, cfs.metadata().name);
+ }
+
+ this.cfs = cfs;
+ this.transaction = transaction;
+ this.outputHandler = outputHandler;
+ this.options = options;
+ this.destination = cfs.getDirectories().getLocationForDisk(cfs.getDiskBoundaries().getCorrectDiskForSSTable(sstable));
+ this.isCommutative = cfs.metadata().isCounter();
+
+ List<SSTableReader> toScrub = Collections.singletonList(sstable);
+
+ long approximateKeyCount;
+ try
+ {
+ approximateKeyCount = SSTableReader.getApproximateKeyCount(toScrub);
+ }
+ catch (RuntimeException ex)
+ {
+ approximateKeyCount = 0;
+ }
+ this.expectedBloomFilterSize = Math.max(cfs.metadata().params.minIndexInterval, approximateKeyCount);
+
+ // loop through each partition, deserializing to check for damage.
+ // We'll also loop through the index at the same time, using the position from the index to recover if the
+ // partition header (key or data size) is corrupt. (This means our position in the index file will be one
+ // partition "ahead" of the data file.)
+ this.dataFile = transaction.isOffline()
+ ? sstable.openDataReader()
+ : sstable.openDataReader(CompactionManager.instance.getRateLimiter());
+
+ this.scrubInfo = new ScrubInfo(dataFile, sstable, fileAccessLock.readLock());
+
+ if (options.reinsertOverflowedTTLRows)
+ outputHandler.output("Starting scrub with reinsert overflowed TTL option");
+ }
+
+ public static void deleteOrphanedComponents(Descriptor descriptor, Set<Component> components)
+ {
+ File dataFile = descriptor.fileFor(Components.DATA);
+ if (components.contains(Components.DATA) && dataFile.length() > 0)
+ // everything appears to be in order... moving on.
+ return;
+
+ // missing the DATA file! all components are orphaned
+ logger.warn("Removing orphans for {}: {}", descriptor, components);
+ for (Component component : components)
+ {
+ File file = descriptor.fileFor(component);
+ if (file.exists())
+ descriptor.fileFor(component).delete();
+ }
+ }
+
+ @Override
+ public void scrub()
+ {
+ List<SSTableReader> finished = new ArrayList<>();
+ outputHandler.output("Scrubbing %s (%s)", sstable, FBUtilities.prettyPrintMemory(dataFile.length()));
+ try (SSTableRewriter writer = SSTableRewriter.construct(cfs, transaction, false, sstable.maxDataAge);
+ Refs<SSTableReader> refs = Refs.ref(Collections.singleton(sstable)))
+ {
+ StatsMetadata metadata = sstable.getSSTableMetadata();
+ writer.switchWriter(CompactionManager.createWriter(cfs, destination, expectedBloomFilterSize, metadata.repairedAt, metadata.pendingRepair, metadata.isTransient, sstable, transaction));
+
+ scrubInternal(writer);
+
+ if (!outOfOrder.isEmpty())
+ finished.add(writeOutOfOrderPartitions(metadata));
+
+ // finish obsoletes the old sstable
+ transaction.obsoleteOriginals();
+ finished.addAll(writer.setRepairedAt(badPartitions > 0 ? ActiveRepairService.UNREPAIRED_SSTABLE : sstable.getSSTableMetadata().repairedAt).finish());
+ }
+ catch (IOException ex)
+ {
+ throw new RuntimeException(ex);
+ }
+ finally
+ {
+ if (transaction.isOffline())
+ finished.forEach(sstable -> sstable.selfRef().release());
+ }
+
+ outputSummary(finished);
+ }
+
+ protected abstract void scrubInternal(SSTableRewriter writer) throws IOException;
+
+ private void outputSummary(List<SSTableReader> finished)
+ {
+ if (!finished.isEmpty())
+ {
+ outputHandler.output("Scrub of %s complete: %d partitions in new sstable and %d empty (tombstoned) partitions dropped", sstable, goodPartitions, emptyPartitions);
+ if (negativeLocalDeletionInfoMetrics.fixedRows > 0)
+ outputHandler.output("Fixed %d rows with overflowed local deletion time.", negativeLocalDeletionInfoMetrics.fixedRows);
+ if (badPartitions > 0)
+ outputHandler.warn("Unable to recover %d partitions that were skipped. You can attempt manual recovery from the pre-scrub snapshot. You can also run nodetool repair to transfer the data from a healthy replica, if any", badPartitions);
+ }
+ else
+ {
+ if (badPartitions > 0)
+ outputHandler.warn("No valid partitions found while scrubbing %s; it is marked for deletion now. If you want to attempt manual recovery, you can find a copy in the pre-scrub snapshot", sstable);
+ else
+ outputHandler.output("Scrub of %s complete; looks like all %d partitions were tombstoned", sstable, emptyPartitions);
+ }
+ }
+
+ private SSTableReader writeOutOfOrderPartitions(StatsMetadata metadata)
+ {
+ // out of order partitions/rows, but no bad partition found - we can keep our repairedAt time
+ long repairedAt = badPartitions > 0 ? ActiveRepairService.UNREPAIRED_SSTABLE : sstable.getSSTableMetadata().repairedAt;
+ SSTableReader newInOrderSstable;
+ try (SSTableWriter inOrderWriter = CompactionManager.createWriter(cfs, destination, expectedBloomFilterSize, repairedAt, metadata.pendingRepair, metadata.isTransient, sstable, transaction))
+ {
+ for (Partition partition : outOfOrder)
+ inOrderWriter.append(partition.unfilteredIterator());
+ inOrderWriter.setRepairedAt(-1);
+ inOrderWriter.setMaxDataAge(sstable.maxDataAge);
+ newInOrderSstable = inOrderWriter.finish(true);
+ }
+ transaction.update(newInOrderSstable, false);
+ outputHandler.warn("%d out of order partition (or partitions without of order rows) found while scrubbing %s; " +
+ "Those have been written (in order) to a new sstable (%s)", outOfOrder.size(), sstable, newInOrderSstable);
+ return newInOrderSstable;
+ }
+
+ protected abstract UnfilteredRowIterator withValidation(UnfilteredRowIterator iter, String filename);
+
+ @Override
+ @VisibleForTesting
+ public ScrubResult scrubWithResult()
+ {
+ scrub();
+ return new ScrubResult(goodPartitions, badPartitions, emptyPartitions);
+ }
+
+ @Override
+ public CompactionInfo.Holder getScrubInfo()
+ {
+ return scrubInfo;
+ }
+
+ protected String keyString(DecoratedKey key)
+ {
+ if (key == null)
+ return "(unknown)";
+
+ try
+ {
+ return cfs.metadata().partitionKeyType.getString(key.getKey());
+ }
+ catch (Exception e)
+ {
+ return String.format("(corrupted; hex value: %s)", ByteBufferUtil.bytesToHex(key.getKey()));
+ }
+ }
+
+ protected boolean tryAppend(DecoratedKey prevKey, DecoratedKey key, SSTableRewriter writer)
+ {
+ // OrderCheckerIterator will check, at iteration time, that the rows are in the proper order. If it detects
+ // that one row is out of order, it will stop returning them. The remaining rows will be sorted and added
+ // to the outOfOrder set that will be later written to a new SSTable.
+ try (OrderCheckerIterator sstableIterator = new OrderCheckerIterator(getIterator(key), cfs.metadata().comparator);
+ UnfilteredRowIterator iterator = withValidation(sstableIterator, dataFile.getPath()))
+ {
+ if (prevKey != null && prevKey.compareTo(key) > 0)
+ {
+ saveOutOfOrderPartition(prevKey, key, iterator);
+ return false;
+ }
+
+ if (writer.tryAppend(iterator) == null)
+ emptyPartitions++;
+ else
+ goodPartitions++;
+
+ if (sstableIterator.hasRowsOutOfOrder())
+ {
+ outputHandler.warn("Out of order rows found in partition: %s", keyString(key));
+ outOfOrder.add(sstableIterator.getRowsOutOfOrder());
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Only wrap with {@link FixNegativeLocalDeletionTimeIterator} if {@link IScrubber.Options#reinsertOverflowedTTLRows} option
+ * is specified
+ */
+ private UnfilteredRowIterator getIterator(DecoratedKey key)
+ {
+ RowMergingSSTableIterator rowMergingIterator = new RowMergingSSTableIterator(SSTableIdentityIterator.create(sstable, dataFile, key), outputHandler);
+ if (options.reinsertOverflowedTTLRows)
+ return new FixNegativeLocalDeletionTimeIterator(rowMergingIterator, outputHandler, negativeLocalDeletionInfoMetrics);
+ else
+ return rowMergingIterator;
+ }
+
+ private void saveOutOfOrderPartition(DecoratedKey prevKey, DecoratedKey key, UnfilteredRowIterator iterator)
+ {
+ // TODO bitch if the row is too large? if it is there's not much we can do ...
+ outputHandler.warn("Out of order partition detected (%s found after %s)", keyString(key), keyString(prevKey));
+ outOfOrder.add(ImmutableBTreePartition.create(iterator));
+ }
+
+ protected static void throwIfFatal(Throwable th)
+ {
+ if (th instanceof Error && !(th instanceof AssertionError || th instanceof IOError))
+ throw (Error) th;
+ }
+
+ protected void throwIfCannotContinue(DecoratedKey key, Throwable th)
+ {
+ if (isCommutative && !options.skipCorrupted)
+ {
+ outputHandler.warn("An error occurred while scrubbing the partition with key '%s'. Skipping corrupt " +
+ "data in counter tables will result in undercounts for the affected " +
+ "counters (see CASSANDRA-2759 for more details), so by default the scrub will " +
+ "stop at this point. If you would like to skip the row anyway and continue " +
+ "scrubbing, re-run the scrub with the --skip-corrupted option.",
+ keyString(key));
+ throw new IOError(th);
+ }
+ }
+
+
+ public static class ScrubInfo extends CompactionInfo.Holder
+ {
+ private final RandomAccessReader dataFile;
+ private final SSTableReader sstable;
+ private final TimeUUID scrubCompactionId;
+ private final Lock fileReadLock;
+
+ public ScrubInfo(RandomAccessReader dataFile, SSTableReader sstable, Lock fileReadLock)
+ {
+ this.dataFile = dataFile;
+ this.sstable = sstable;
+ this.fileReadLock = fileReadLock;
+ scrubCompactionId = nextTimeUUID();
+ }
+
+ public CompactionInfo getCompactionInfo()
+ {
+ fileReadLock.lock();
+ try
+ {
+ return new CompactionInfo(sstable.metadata(),
+ OperationType.SCRUB,
+ dataFile.getFilePointer(),
+ dataFile.length(),
+ scrubCompactionId,
+ ImmutableSet.of(sstable),
- Paths.get(sstable.getFilename()).getParent().toString());
++ File.getPath(sstable.getFilename()).getParent().toString());
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException(e);
+ }
+ finally
+ {
+ fileReadLock.unlock();
+ }
+ }
+
+ public boolean isGlobal()
+ {
+ return false;
+ }
+ }
+
+ /**
+ * In some case like CASSANDRA-12127 the cells might have been stored in the wrong order. This decorator check the
+ * cells order and collect the out-of-order cells to correct the problem.
+ */
+ private static final class OrderCheckerIterator extends AbstractIterator<Unfiltered> implements WrappingUnfilteredRowIterator
+ {
+ private final UnfilteredRowIterator iterator;
+ private final ClusteringComparator comparator;
+
+ private Unfiltered previous;
+
+ /**
+ * The partition containing the rows which are out of order.
+ */
+ private Partition rowsOutOfOrder;
+
+ public OrderCheckerIterator(UnfilteredRowIterator iterator, ClusteringComparator comparator)
+ {
+ this.iterator = iterator;
+ this.comparator = comparator;
+ }
+
+ @Override
+ public UnfilteredRowIterator wrapped()
+ {
+ return iterator;
+ }
+
+ public boolean hasRowsOutOfOrder()
+ {
+ return rowsOutOfOrder != null;
+ }
+
+ public Partition getRowsOutOfOrder()
+ {
+ return rowsOutOfOrder;
+ }
+
+ @Override
+ protected Unfiltered computeNext()
+ {
+ if (!iterator.hasNext())
+ return endOfData();
+
+ Unfiltered next = iterator.next();
+
+ // If we detect that some rows are out of order we will store and sort the remaining ones to insert them
+ // in a separate SSTable.
+ if (previous != null && comparator.compare(next, previous) < 0)
+ {
+ rowsOutOfOrder = ImmutableBTreePartition.create(UnfilteredRowIterators.concat(next, iterator), false);
+ return endOfData();
+ }
+ previous = next;
+ return next;
+ }
+ }
+
+ /**
+ * During 2.x migration, under some circumstances rows might have gotten duplicated.
+ * Merging iterator merges rows with same clustering.
+ * <p>
+ * For more details, refer to CASSANDRA-12144.
+ */
+ private static class RowMergingSSTableIterator implements WrappingUnfilteredRowIterator
+ {
+ Unfiltered nextToOffer = null;
+ private final OutputHandler output;
+ private final UnfilteredRowIterator wrapped;
+
+ RowMergingSSTableIterator(UnfilteredRowIterator source, OutputHandler output)
+ {
+ this.wrapped = source;
+ this.output = output;
+ }
+
+ @Override
+ public UnfilteredRowIterator wrapped()
+ {
+ return wrapped;
+ }
+
+ @Override
+ public boolean hasNext()
+ {
+ return nextToOffer != null || wrapped.hasNext();
+ }
+
+ @Override
+ public Unfiltered next()
+ {
+ Unfiltered next = nextToOffer != null ? nextToOffer : wrapped.next();
+
+ if (next.isRow())
+ {
+ boolean logged = false;
+ while (wrapped.hasNext())
+ {
+ Unfiltered peek = wrapped.next();
+ if (!peek.isRow() || !next.clustering().equals(peek.clustering()))
+ {
+ nextToOffer = peek; // Offer peek in next call
+ return next;
+ }
+
+ // Duplicate row, merge it.
+ next = Rows.merge((Row) next, (Row) peek);
+
+ if (!logged)
+ {
+ String partitionKey = metadata().partitionKeyType.getString(partitionKey().getKey());
+ output.warn("Duplicate row detected in %s.%s: %s %s", metadata().keyspace, metadata().name, partitionKey, next.clustering().toString(metadata()));
+ logged = true;
+ }
+ }
+ }
+
+ nextToOffer = null;
+ return next;
+ }
+ }
+
+ /**
+ * This iterator converts negative {@link AbstractCell#localDeletionTime()} into {@link AbstractCell#MAX_DELETION_TIME}
+ * <p>
+ * This is to recover entries with overflowed localExpirationTime due to CASSANDRA-14092
+ */
+ private static final class FixNegativeLocalDeletionTimeIterator extends AbstractIterator<Unfiltered> implements WrappingUnfilteredRowIterator
+ {
+ /**
+ * The decorated iterator.
+ */
+ private final UnfilteredRowIterator iterator;
+
+ private final OutputHandler outputHandler;
+ private final NegativeLocalDeletionInfoMetrics negativeLocalExpirationTimeMetrics;
+
+ public FixNegativeLocalDeletionTimeIterator(UnfilteredRowIterator iterator, OutputHandler outputHandler,
+ NegativeLocalDeletionInfoMetrics negativeLocalDeletionInfoMetrics)
+ {
+ this.iterator = iterator;
+ this.outputHandler = outputHandler;
+ this.negativeLocalExpirationTimeMetrics = negativeLocalDeletionInfoMetrics;
+ }
+
+ @Override
+ public UnfilteredRowIterator wrapped()
+ {
+ return iterator;
+ }
+
+ @Override
+ protected Unfiltered computeNext()
+ {
+ if (!iterator.hasNext())
+ return endOfData();
+
+ Unfiltered next = iterator.next();
+ if (!next.isRow())
+ return next;
+
+ if (hasNegativeLocalExpirationTime((Row) next))
+ {
+ outputHandler.debug("Found row with negative local expiration time: %s", next.toString(metadata(), false));
+ negativeLocalExpirationTimeMetrics.fixedRows++;
+ return fixNegativeLocalExpirationTime((Row) next);
+ }
+
+ return next;
+ }
+
+ private boolean hasNegativeLocalExpirationTime(Row next)
+ {
+ Row row = next;
+ if (row.primaryKeyLivenessInfo().isExpiring() && row.primaryKeyLivenessInfo().localExpirationTime() < 0)
+ {
+ return true;
+ }
+
+ for (ColumnData cd : row)
+ {
+ if (cd.column().isSimple())
+ {
+ Cell<?> cell = (Cell<?>) cd;
+ if (cell.isExpiring() && cell.localDeletionTime() < 0)
+ return true;
+ }
+ else
+ {
+ ComplexColumnData complexData = (ComplexColumnData) cd;
+ for (Cell<?> cell : complexData)
+ {
+ if (cell.isExpiring() && cell.localDeletionTime() < 0)
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private Unfiltered fixNegativeLocalExpirationTime(Row row)
+ {
+ LivenessInfo livenessInfo = row.primaryKeyLivenessInfo();
+ if (livenessInfo.isExpiring() && livenessInfo.localExpirationTime() < 0)
+ livenessInfo = livenessInfo.withUpdatedTimestampAndLocalDeletionTime(livenessInfo.timestamp() + 1, AbstractCell.MAX_DELETION_TIME);
+
+ return row.transformAndFilter(livenessInfo, row.deletion(), cd -> {
+ if (cd.column().isSimple())
+ {
+ Cell cell = (Cell) cd;
+ return cell.isExpiring() && cell.localDeletionTime() < 0
+ ? cell.withUpdatedTimestampAndLocalDeletionTime(cell.timestamp() + 1, AbstractCell.MAX_DELETION_TIME)
+ : cell;
+ }
+ else
+ {
+ ComplexColumnData complexData = (ComplexColumnData) cd;
+ return complexData.transformAndFilter(cell -> cell.isExpiring() && cell.localDeletionTime() < 0
+ ? cell.withUpdatedTimestampAndLocalDeletionTime(cell.timestamp() + 1, AbstractCell.MAX_DELETION_TIME)
+ : cell);
+ }
+ }).clone(HeapCloner.instance);
+ }
+ }
+
+ private static class NegativeLocalDeletionInfoMetrics
+ {
+ public volatile int fixedRows = 0;
+ }
+}
diff --cc src/java/org/apache/cassandra/io/util/File.java
index 3b6bbb68a4,1f48707910..c9bc97c3a9
--- a/src/java/org/apache/cassandra/io/util/File.java
+++ b/src/java/org/apache/cassandra/io/util/File.java
@@@ -23,12 -23,7 +23,12 @@@ import java.io.IOException
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.channels.FileChannel;
-import java.nio.file.*; // checkstyle: permit this import
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
- import java.nio.file.Paths;
++import java.nio.file.Paths; // checkstyle: permit this import
import java.util.Objects;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
@@@ -132,11 -127,17 +131,16 @@@ public class File implements Comparable
public File(Path path)
{
if (path != null && path.getFileSystem() != filesystem)
-- throw new IllegalArgumentException("Incompatible file system");
++ throw new IllegalArgumentException("Incompatible file system; path FileSystem (" + path.getFileSystem() + ") is not the same reference (" + filesystem + ")");
this.path = path;
}
-
+ public static Path getPath(String first, String... more)
+ {
+ return filesystem.getPath(first, more);
+ }
+
/**
* Try to delete the file, returning true iff it was deleted by us. Does not ordinarily throw exceptions.
*/
diff --cc src/java/org/apache/cassandra/security/FileBasedSslContextFactory.java
index 5b3ca124ff,aee9ba1ab6..826e3152f0
--- a/src/java/org/apache/cassandra/security/FileBasedSslContextFactory.java
+++ b/src/java/org/apache/cassandra/security/FileBasedSslContextFactory.java
@@@ -152,7 -158,7 +151,7 @@@ public abstract class FileBasedSslConte
@Override
protected TrustManagerFactory buildTrustManagerFactory() throws SSLException
{
- try (InputStream tsf = Files.newInputStream(Paths.get(trustStoreContext.filePath)))
- try (InputStream tsf = Files.newInputStream(File.getPath(truststore)))
++ try (InputStream tsf = Files.newInputStream(File.getPath(trustStoreContext.filePath)))
{
final String algorithm = this.algorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : this.algorithm;
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
@@@ -167,29 -173,6 +166,29 @@@
}
}
+ private KeyManagerFactory getKeyManagerFactory(final FileBasedStoreContext context) throws SSLException
+ {
- try (InputStream ksf = Files.newInputStream(Paths.get(context.filePath)))
++ try (InputStream ksf = Files.newInputStream(File.getPath(context.filePath)))
+ {
+ final String algorithm = this.algorithm == null ? KeyManagerFactory.getDefaultAlgorithm() : this.algorithm;
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
+ KeyStore ks = KeyStore.getInstance(store_type);
+ ks.load(ksf, context.password.toCharArray());
+
+ if (!context.checkedExpiry)
+ {
+ checkExpiredCerts(ks);
+ context.checkedExpiry = true;
+ }
+ kmf.init(ks, context.password.toCharArray());
+ return kmf;
+ }
+ catch (Exception e)
+ {
+ throw new SSLException("failed to build key manager store for secure connections", e);
+ }
+ }
+
protected boolean checkExpiredCerts(KeyStore ks) throws KeyStoreException
{
boolean hasExpiredCerts = false;
diff --cc src/java/org/apache/cassandra/service/StorageService.java
index 09948093de,6d0d24eb94..a7c743fd71
--- a/src/java/org/apache/cassandra/service/StorageService.java
+++ b/src/java/org/apache/cassandra/service/StorageService.java
@@@ -25,29 -26,9 +25,28 @@@ import java.net.InetAddress
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
- import java.nio.file.Paths;
import java.time.Instant;
-import java.util.*;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Scanner;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
diff --cc src/java/org/apache/cassandra/utils/HeapUtils.java
index 504855bbe1,c0910d87fc..38a6969908
--- a/src/java/org/apache/cassandra/utils/HeapUtils.java
+++ b/src/java/org/apache/cassandra/utils/HeapUtils.java
@@@ -22,15 -22,11 +22,14 @@@ import java.io.BufferedReader
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
+import java.nio.file.FileStore;
+import java.nio.file.Path;
- import java.nio.file.Paths;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import javax.management.MBeanServer;
-import org.apache.cassandra.io.util.File;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.text.StrBuilder;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@@ -85,72 -73,6 +84,72 @@@ public final class HeapUtil
}
}
+ /**
+ * @return full path to the created heap dump file
+ */
+ public static String maybeCreateHeapDump()
+ {
+ // Make sure that only one heap dump can be in progress across all threads, and abort for
+ // threads that cannot immediately acquire the lock, allowing them to fail normally.
+ if (DUMP_LOCK.tryLock())
+ {
+ try
+ {
+ if (DatabaseDescriptor.getDumpHeapOnUncaughtException())
+ {
+ MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+
+ Path absoluteBasePath = DatabaseDescriptor.getHeapDumpPath();
+ // We should never reach this point with this value null as we initialize the bool only after confirming
+ // the -XX param / .yaml conf is present on initial init and the JMX entry point, but still worth checking.
+ if (absoluteBasePath == null)
+ {
+ DatabaseDescriptor.setDumpHeapOnUncaughtException(false);
+ throw new RuntimeException("Cannot create heap dump unless -XX:HeapDumpPath or cassandra.yaml:heap_dump_path is specified.");
+ }
+
+ long maxMemoryBytes = Runtime.getRuntime().maxMemory();
+ long freeSpaceBytes = PathUtils.tryGetSpace(absoluteBasePath, FileStore::getUnallocatedSpace);
+
+ // Abort if there isn't enough room on the target disk to dump the entire heap and then copy it.
+ if (freeSpaceBytes < 2 * maxMemoryBytes)
+ throw new RuntimeException("Cannot allocated space for a heap dump snapshot. There are only " + freeSpaceBytes + " bytes free at " + absoluteBasePath + '.');
+
+ HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
+ String filename = String.format("pid%s-epoch%s.hprof", HeapUtils.getProcessId().toString(), currentTimeMillis());
- String fullPath = Paths.get(absoluteBasePath.toString(), filename).toString();
++ String fullPath = File.getPath(absoluteBasePath.toString(), filename).toString();
+
+ logger.info("Writing heap dump to {} on partition w/ {} free bytes...", absoluteBasePath, freeSpaceBytes);
+ mxBean.dumpHeap(fullPath, false);
+ logger.info("Heap dump written to {}", fullPath);
+
+ // Disable further heap dump creations until explicitly re-enabled.
+ DatabaseDescriptor.setDumpHeapOnUncaughtException(false);
+
+ return fullPath;
+ }
+ else
+ {
+ logger.debug("Heap dump creation on uncaught exceptions is disabled.");
+ }
+ }
+ catch (Throwable e)
+ {
+ logger.warn("Unable to create heap dump.", e);
+ }
+ finally
+ {
+ DUMP_LOCK.unlock();
+ }
+ }
+ else
+ {
+ logger.debug("Heap dump creation is already in progress. Request aborted.");
+ }
+
+ return null;
+ }
+
/**
* Retrieve the path to the JCMD executable.
* @return the path to the JCMD executable or null if it cannot be found.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org