You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by ma...@apache.org on 2022/03/28 20:49:08 UTC
[cassandra] branch trunk updated (813e6ae -> 7b58b79)
This is an automated email from the ASF dual-hosted git repository.
maedhroz pushed a change to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra.git.
from 813e6ae Revert "change six functions in cqlshlib to native Python 3 ones"
new 0089858 Shut repair task executor down without interruption to avoid compromising shared channel proxies
new 7b58b79 Merge branch 'cassandra-4.0' 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:
CHANGES.txt | 1 +
.../org/apache/cassandra/repair/LocalSyncTask.java | 70 +++++++++---
.../org/apache/cassandra/repair/RepairJob.java | 23 ++--
.../apache/cassandra/repair/RepairRunnable.java | 2 +-
.../org/apache/cassandra/repair/RepairSession.java | 25 ++++-
.../org/apache/cassandra/repair/SnapshotTask.java | 3 +-
src/java/org/apache/cassandra/repair/SyncTask.java | 4 +-
.../cassandra/service/ActiveRepairService.java | 6 ++
.../apache/cassandra/streaming/SessionInfo.java | 5 +
.../cassandra/streaming/StreamCoordinator.java | 3 +-
.../cassandra/streaming/StreamResultFuture.java | 6 ++
.../apache/cassandra/streaming/StreamSession.java | 80 +++++++++-----
.../apache/cassandra/streaming/StreamState.java | 14 ++-
.../distributed/test/RepairErrorsTest.java | 119 +++++++++++++++++++--
14 files changed, 288 insertions(+), 73 deletions(-)
---------------------------------------------------------------------
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.0' into trunk
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
maedhroz pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra.git
commit 7b58b79fe24c612f8bbf7984c325e88496f482d6
Merge: 813e6ae 0089858
Author: Caleb Rackliffe <ca...@gmail.com>
AuthorDate: Mon Mar 28 15:35:25 2022 -0500
Merge branch 'cassandra-4.0' into trunk
CHANGES.txt | 1 +
.../org/apache/cassandra/repair/LocalSyncTask.java | 70 +++++++++---
.../org/apache/cassandra/repair/RepairJob.java | 23 ++--
.../apache/cassandra/repair/RepairRunnable.java | 2 +-
.../org/apache/cassandra/repair/RepairSession.java | 25 ++++-
.../org/apache/cassandra/repair/SnapshotTask.java | 3 +-
src/java/org/apache/cassandra/repair/SyncTask.java | 4 +-
.../cassandra/service/ActiveRepairService.java | 6 ++
.../apache/cassandra/streaming/SessionInfo.java | 5 +
.../cassandra/streaming/StreamCoordinator.java | 3 +-
.../cassandra/streaming/StreamResultFuture.java | 6 ++
.../apache/cassandra/streaming/StreamSession.java | 80 +++++++++-----
.../apache/cassandra/streaming/StreamState.java | 14 ++-
.../distributed/test/RepairErrorsTest.java | 119 +++++++++++++++++++--
14 files changed, 288 insertions(+), 73 deletions(-)
diff --cc CHANGES.txt
index 75a6475,8fcebb0..3e59bc0
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@@ -1,122 -1,5 +1,123 @@@
-4.0.4
+4.1
+ * Disallow removing DC from system_auth while nodes are active in the DC (CASSANDRA-17478)
+ * Add guardrail for the number of fields per UDT (CASSANDRA-17385)
+ * Allow users to change cqlsh history location using env variable (CASSANDRA-17448)
+ * Add required -f option to use nodetool verify and standalone sstableverify (CASSANDRA-17017)
+ * Add support for UUID based sstable generation identifiers (CASSANDRA-17048)
+ * Log largest memtable flush at info instead of debug (CASSANDRA-17472)
+ * Add native transport rate limiter options to example cassandra.yaml, and expose metric for dispatch rate (CASSANDRA-17423)
+ * Add diagnostic events for guardrails (CASSANDRA-17197)
+ * Pre hashed passwords in CQL (CASSANDRA-17334)
+ * Increase cqlsh version (CASSANDRA-17432)
+ * Update SUPPORTED_UPGRADE_PATHS to include 3.0 and 3.x to 4.1 paths and remove obsolete tests (CASSANDRA-17362)
+ * Support DELETE in CQLSSTableWriter (CASSANDRA-14797)
+ * Failed inbound internode authentication failures generate ugly warning with stack trace (CASSANDRA-17068)
+ * Expose gossip information in system_views.gossip_info virtual table (CASSANDRA-17002)
+ * Add guardrails for collection items and size (CASSANDRA-17153)
+ * Improve guardrails messages (CASSANDRA-17430)
+ * Remove all usages of junit.framework and ban them via Checkstyle (CASSANDRA-17316)
+ * Add guardrails for read/write consistency levels (CASSANDRA-17188)
+ * Add guardrail for SELECT IN terms and their cartesian product (CASSANDRA-17187)
+ * remove unused imports in cqlsh.py and cqlshlib (CASSANDRA-17413)
+ * deprecate property windows_timer_interval (CASSANDRA-17404)
+ * Expose streaming as a vtable (CASSANDRA-17390)
+ * Expose all client options via system_views.clients and nodetool clientstats (CASSANDRA-16378)
+ * Make startup checks configurable (CASSANDRA-17220)
+ * Add guardrail for number of partition keys on IN queries (CASSANDRA-17186)
+ * update Python test framework from nose to pytest (CASSANDRA-17293)
+ * Fix improper CDC commit log segments deletion in non-blocking mode (CASSANDRA-17233)
+ * Add support for string concatenations through the + operator (CASSANDRA-17190)
+ * Limit the maximum hints size per host (CASSANDRA-17142)
+ * Add a virtual table for exposing batch metrics (CASSANDRA-17225)
+ * Flatten guardrails config (CASSANDRA-17353)
+ * Instance failed to start up due to NPE in StartupClusterConnectivityChecker (CASSANDRA-17347)
+ * add the shorter version of version flag (-v) in cqlsh (CASSANDRA-17236)
+ * Make vtables accessible via internode messaging (CASSANDRA-17295)
+ * Add support for PEM based key material for SSL (CASSANDRA-17031)
+ * Standardize storage configuration parameters' names. Support unit suffixes. (CASSANDRA-15234)
+ * Remove support for Windows (CASSANDRA-16956)
+ * Runtime-configurable YAML option to prohibit USE statements (CASSANDRA-17318)
+ * When streaming sees a ClosedChannelException this triggers the disk failure policy (CASSANDRA-17116)
+ * Add a virtual table for exposing prepared statements metrics (CASSANDRA-17224)
+ * Remove python 2.x support from cqlsh (CASSANDRA-17242)
+ * Prewarm role and credential caches to avoid timeouts at startup (CASSANDRA-16958)
+ * Make capacity/validity/updateinterval/activeupdate for Auth Caches configurable via nodetool (CASSANDRA-17063)
+ * Added startup check for read_ahead_kb setting (CASSANDRA-16436)
+ * Avoid unecessary array allocations and initializations when performing query checks (CASSANDRA-17209)
+ * Add guardrail for list operations that require read before write (CASSANDRA-17154)
+ * Migrate thresholds for number of keyspaces and tables to guardrails (CASSANDRA-17195)
+ * Remove self-reference in SSTableTidier (CASSANDRA-17205)
+ * Add guardrail for query page size (CASSANDRA-17189)
+ * Allow column_index_size_in_kb to be configurable through nodetool (CASSANDRA-17121)
+ * Emit a metric for number of local read and write calls
+ * Add non-blocking mode for CDC writes (CASSANDRA-17001)
+ * Add guardrails framework (CASSANDRA-17147)
+ * Harden resource management on SSTable components to prevent future leaks (CASSANDRA-17174)
+ * Make nodes more resilient to local unrelated files during startup (CASSANDRA-17082)
+ * repair prepare message would produce a wrong error message if network timeout happened rather than reply wait timeout (CASSANDRA-16992)
+ * Log queries that fail on timeout or unavailable errors up to once per minute by default (CASSANDRA-17159)
+ * Refactor normal/preview/IR repair to standardize repair cleanup and error handling of failed RepairJobs (CASSANDRA-17069)
+ * Log missing peers in StartupClusterConnectivityChecker (CASSANDRA-17130)
+ * Introduce separate rate limiting settings for entire SSTable streaming (CASSANDRA-17065)
+ * Implement Virtual Tables for Auth Caches (CASSANDRA-16914)
+ * Actively update auth cache in the background (CASSANDRA-16957)
+ * Add unix time conversion functions (CASSANDRA-17029)
+ * JVMStabilityInspector.forceHeapSpaceOomMaybe should handle all non-heap OOMs rather than only supporting direct only (CASSANDRA-17128)
+ * Forbid other Future implementations with checkstyle (CASSANDRA-17055)
+ * commit log was switched from non-daemon to daemon threads, which causes the JVM to exit in some case as no non-daemon threads are active (CASSANDRA-17085)
+ * Add a Denylist to block reads and writes on specific partition keys (CASSANDRA-12106)
+ * v4+ protocol did not clean up client warnings, which caused leaking the state (CASSANDRA-17054)
+ * Remove duplicate toCQLString in ReadCommand (CASSANDRA-17023)
+ * Ensure hint window is persistent across restarts of a node (CASSANDRA-14309)
+ * Allow to GRANT or REVOKE multiple permissions in a single statement (CASSANDRA-17030)
+ * Allow to grant permission for all tables in a keyspace (CASSANDRA-17027)
+ * Log time spent writing keys during compaction (CASSANDRA-17037)
+ * Make nodetool compactionstats and sstable_tasks consistent (CASSANDRA-16976)
+ * Add metrics and logging around index summary redistribution (CASSANDRA-17036)
+ * Add configuration options for minimum allowable replication factor and default replication factor (CASSANDRA-14557)
+ * Expose information about stored hints via a nodetool command and a virtual table (CASSANDRA-14795)
+ * Add broadcast_rpc_address to system.local (CASSANDRA-11181)
+ * Add support for type casting in WHERE clause components and in the values of INSERT/UPDATE statements (CASSANDRA-14337)
+ * add credentials file support to CQLSH (CASSANDRA-16983)
+ * Skip remaining bytes in the Envelope buffer when a ProtocolException is thrown to avoid double decoding (CASSANDRA-17026)
+ * Allow reverse iteration of resources during permissions checking (CASSANDRA-17016)
+ * Add feature to verify correct ownership of attached locations on disk at startup (CASSANDRA-16879)
+ * Make SSLContext creation pluggable/extensible (CASSANDRA-16666)
+ * Add soft/hard limits to local reads to protect against reading too much data in a single query (CASSANDRA-16896)
+ * Avoid token cache invalidation for removing a non-member node (CASSANDRA-15290)
+ * Allow configuration of consistency levels on auth operations (CASSANDRA-12988)
+ * Add number of sstables in a compaction to compactionstats output (CASSANDRA-16844)
+ * Upgrade Caffeine to 2.9.2 (CASSANDRA-15153)
+ * Allow DELETE and TRUNCATE to work on Virtual Tables if the implementation allows it (CASSANDRA-16806)
+ * Include SASI components to snapshots (CASSANDRA-15134)
+ * Fix missed wait latencies in the output of `nodetool tpstats -F` (CASSANDRA-16938)
+ * Reduce native transport max frame size to 16MB (CASSANDRA-16886)
+ * Add support for filtering using IN restrictions (CASSANDRA-14344)
+ * Provide a nodetool command to invalidate auth caches (CASSANDRA-16404)
+ * Catch read repair timeout exceptions and add metric (CASSANDRA-16880)
+ * Exclude Jackson 1.x transitive dependency of hadoop* provided dependencies (CASSANDRA-16854)
+ * Add client warnings and abort to tombstone and coordinator reads which go past a low/high watermark (CASSANDRA-16850)
+ * Add TTL support to nodetool snapshots (CASSANDRA-16789)
+ * Allow CommitLogSegmentReader to optionally skip sync marker CRC checks (CASSANDRA-16842)
+ * allow blocking IPs from updating metrics about traffic (CASSANDRA-16859)
+ * Request-Based Native Transport Rate-Limiting (CASSANDRA-16663)
+ * Implement nodetool getauditlog command (CASSANDRA-16725)
+ * Clean up repair code (CASSANDRA-13720)
+ * Background schedule to clean up orphaned hints files (CASSANDRA-16815)
+ * Modify SecondaryIndexManager#indexPartition() to retrieve only columns for which indexes are actually being built (CASSANDRA-16776)
+ * Batch the token metadata update to improve the speed (CASSANDRA-15291)
+ * Reduce the log level on "expected" repair exceptions (CASSANDRA-16775)
+ * Make JMXTimer expose attributes using consistent time unit (CASSANDRA-16760)
+ * Remove check on gossip status from DynamicEndpointSnitch::updateScores (CASSANDRA-11671)
+ * Fix AbstractReadQuery::toCQLString not returning valid CQL (CASSANDRA-16510)
+ * Log when compacting many tombstones (CASSANDRA-16780)
+ * Display bytes per level in tablestats for LCS tables (CASSANDRA-16799)
+ * Add isolated flush timer to CommitLogMetrics and ensure writes correspond to single WaitingOnCommit data points (CASSANDRA-16701)
+ * Add a system property to set hostId if not yet initialized (CASSANDRA-14582)
+ * GossiperTest.testHasVersion3Nodes didn't take into account trunk version changes, fixed to rely on latest version (CASSANDRA-16651)
+ * Update JNA library to 5.9.0 and snappy-java to version 1.1.8.4 (CASSANDRA-17040)
+Merged from 4.0:
+ * Shut repair task executor down without interruption to avoid compromising shared channel proxies (CASSANDRA-17466)
* Generate valid KEYSPACE / MATERIALIZED VIEW for CQL for views (CASSANDRA-17266)
* Fix timestamp tz parsing (CASSANDRA-17467)
* Suppress CVE-2021-44521 from driver (CASSANDRA-17459)
diff --cc src/java/org/apache/cassandra/repair/LocalSyncTask.java
index a721a87,ffa786c..71cec28
--- a/src/java/org/apache/cassandra/repair/LocalSyncTask.java
+++ b/src/java/org/apache/cassandra/repair/LocalSyncTask.java
@@@ -57,8 -58,11 +58,11 @@@ public class LocalSyncTask extends Sync
@VisibleForTesting
public final boolean transferRanges;
+ private boolean active = true;
+ private StreamPlan streamPlan;
+
public LocalSyncTask(RepairJobDesc desc, InetAddressAndPort local, InetAddressAndPort remote,
- List<Range<Token>> diff, UUID pendingRepair,
+ List<Range<Token>> diff, TimeUUID pendingRepair,
boolean requestRanges, boolean transferRanges, PreviewKind previewKind)
{
super(desc, local, remote, diff, previewKind);
@@@ -144,19 -152,31 +152,31 @@@
}
}
- public void onSuccess(StreamState result)
+ @Override
+ public synchronized void onSuccess(StreamState result)
{
- String message = String.format("Sync complete using session %s between %s and %s on %s", desc.sessionId, nodePair.coordinator, nodePair.peer, desc.columnFamily);
- logger.info("{} {}", previewKind.logPrefix(desc.sessionId), message);
- Tracing.traceRepair(message);
- trySuccess(stat.withSummaries(result.createSummaries()));
- finished();
+ if (active)
+ {
+ active = false;
+ String status = result.hasAbortedSession() ? "aborted" : "complete";
+ String message = String.format("Sync %s using session %s between %s and %s on %s",
+ status, desc.sessionId, nodePair.coordinator, nodePair.peer, desc.columnFamily);
+ logger.info("{} {}", previewKind.logPrefix(desc.sessionId), message);
+ Tracing.traceRepair(message);
- set(result.hasAbortedSession() ? stat : stat.withSummaries(result.createSummaries()));
++ trySuccess(result.hasAbortedSession() ? stat : stat.withSummaries(result.createSummaries()));
+ finished();
+ }
}
- public void onFailure(Throwable t)
+ @Override
+ public synchronized void onFailure(Throwable t)
{
- tryFailure(t);
- finished();
+ if (active)
+ {
+ active = false;
- setException(t);
++ tryFailure(t);
+ finished();
+ }
}
@Override
@@@ -169,4 -189,24 +189,24 @@@
", nodePair=" + nodePair +
'}';
}
+
+ @Override
+ public synchronized void abort()
+ {
+ if (active)
+ {
+ if (streamPlan == null)
+ {
+ active = false;
+ String message = String.format("Sync for session %s between %s and %s on %s aborted before starting",
+ desc.sessionId, nodePair.coordinator, nodePair.peer, desc.columnFamily);
+ logger.debug("{} {}", previewKind.logPrefix(desc.sessionId), message);
- set(stat);
++ trySuccess(stat);
+ }
+ else
+ {
+ streamPlan.getCoordinator().getAllStreamSessions().forEach(StreamSession::abort);
+ }
+ }
+ }
}
diff --cc src/java/org/apache/cassandra/repair/RepairJob.java
index 33234e2,a9ac6af..c6c0bdc
--- a/src/java/org/apache/cassandra/repair/RepairJob.java
+++ b/src/java/org/apache/cassandra/repair/RepairJob.java
@@@ -69,10 -57,9 +70,13 @@@ public class RepairJob extends AsyncFut
private final RepairSession session;
private final RepairJobDesc desc;
private final RepairParallelism parallelismDegree;
- private final ListeningExecutorService taskExecutor;
-
- private final List<SyncTask> syncTasks = new CopyOnWriteArrayList<>();
+ private final ExecutorPlus taskExecutor;
+
+ @VisibleForTesting
- final List<ValidationTask> validationTasks = new ArrayList<>();
++ final List<ValidationTask> validationTasks = new CopyOnWriteArrayList<>();
++
++ @VisibleForTesting
++ final List<SyncTask> syncTasks = new CopyOnWriteArrayList<>();
/**
* Create repair job to run on specific columnfamily
@@@ -106,7 -94,7 +110,6 @@@
* This sets up necessary task and runs them on given {@code taskExecutor}.
* After submitting all tasks, waits until validation with replica completes.
*/
-- @SuppressWarnings("UnstableApiUsage")
public void run()
{
Keyspace ks = Keyspace.open(desc.keyspace);
@@@ -190,11 -145,14 +193,12 @@@
}
// When all validations complete, submit sync tasks
- ListenableFuture<List<SyncStat>> syncResults = Futures.transformAsync(validations,
- session.optimiseStreams && !session.pullRepair ? this::optimisedSyncing : this::standardSyncing,
- taskExecutor);
+ Future<List<SyncStat>> syncResults = treeResponses.flatMap(session.optimiseStreams && !session.pullRepair ? this::optimisedSyncing : this::standardSyncing, taskExecutor);
// When all sync complete, set the final result
- Futures.addCallback(syncResults, new FutureCallback<List<SyncStat>>()
+ syncResults.addCallback(new FutureCallback<List<SyncStat>>()
{
+ @Override
public void onSuccess(List<SyncStat> stats)
{
if (!session.previewKind.isPreview())
@@@ -209,11 -167,11 +213,13 @@@
/**
* Snapshot, validation and sync failures are all handled here
*/
+ @Override
public void onFailure(Throwable t)
{
+ // Make sure all validation tasks have cleaned up the off-heap Merkle trees they might contain.
+ validationTasks.forEach(ValidationTask::abort);
-
+ syncTasks.forEach(SyncTask::abort);
+
if (!session.previewKind.isPreview())
{
logger.warn("{} {}.{} sync failed", session.previewKind.logPrefix(session.getId()), desc.keyspace, desc.columnFamily);
@@@ -324,41 -280,22 +330,42 @@@
return executeTasks(syncTasks);
}
-- @SuppressWarnings("UnstableApiUsage")
@VisibleForTesting
- Future<List<SyncStat>> executeTasks(List<SyncTask> syncTasks)
- ListenableFuture<List<SyncStat>> executeTasks(List<SyncTask> tasks)
++ Future<List<SyncStat>> executeTasks(List<SyncTask> tasks)
{
- // this throws if the parent session has failed
- ActiveRepairService.instance.getParentRepairSession(desc.parentSessionId);
- syncTasks.addAll(tasks);
+ try
+ {
+ ActiveRepairService.instance.getParentRepairSession(desc.parentSessionId);
- for (SyncTask task : syncTasks)
++ syncTasks.addAll(tasks);
+
- for (SyncTask task : tasks)
++ for (SyncTask task : tasks)
+ {
+ if (!task.isLocal())
+ session.trackSyncCompletion(Pair.create(desc, task.nodePair()), (CompletableRemoteSyncTask) task);
+ taskExecutor.execute(task);
+ }
+
- return FutureCombiner.allOf(syncTasks);
++ return FutureCombiner.allOf(tasks);
+ }
+ catch (NoSuchRepairSessionException e)
{
- if (!task.isLocal())
- session.trackSyncCompletion(Pair.create(desc, task.nodePair()), (CompletableRemoteSyncTask) task);
- taskExecutor.submit(task);
+ throw new NoSuchRepairSessionExceptionWrapper(e);
}
+ }
- return Futures.allAsList(tasks);
+ // provided so we can throw NoSuchRepairSessionException from executeTasks without
+ // having to make it unchecked. Required as this is called as from standardSyncing/
+ // optimisedSyncing passed as a Function to transform merkle tree responses and so
+ // can't throw checked exceptions. These are unwrapped in the onFailure callback of
+ // that transformation so as to not pollute the checked usage of
+ // NoSuchRepairSessionException in the rest of the codebase.
+ private static class NoSuchRepairSessionExceptionWrapper extends RuntimeException
+ {
+ private final NoSuchRepairSessionException wrapped;
+ private NoSuchRepairSessionExceptionWrapper(NoSuchRepairSessionException wrapped)
+ {
+ this.wrapped = wrapped;
+ }
}
static List<SyncTask> createOptimisedSyncingSyncTasks(RepairJobDesc desc,
diff --cc src/java/org/apache/cassandra/repair/RepairRunnable.java
index 7ad2c49,48a7e36..a40a713
--- a/src/java/org/apache/cassandra/repair/RepairRunnable.java
+++ b/src/java/org/apache/cassandra/repair/RepairRunnable.java
@@@ -444,24 -535,218 +444,24 @@@ public class RepairRunnable implements
}
else
{
- message = (previewKind == PreviewKind.REPAIRED ? "Repaired data is inconsistent\n" : "Preview complete\n") + summary.toString();
- RepairMetrics.previewFailures.inc();
- if (previewKind == PreviewKind.REPAIRED)
- maybeSnapshotReplicas(parentSession, keyspace, results);
+ success(task.name() + " completed successfully");
+ ActiveRepairService.instance.cleanUp(parentSession, neighborsAndRanges.participants);
}
- notification(message);
-
- success("Repair preview completed successfully");
- ActiveRepairService.instance.cleanUp(parentSession, preparedEndpoints);
- }
- catch (Throwable t)
- {
- logger.error("Error completing preview repair", t);
- onFailure(t);
- }
- finally
- {
- executor.shutdown();
}
}
-
- public void onFailure(Throwable t)
+ finally
{
- executor.shutdownNow();
- notifyError(t);
- fail("Error completing preview repair: " + t.getMessage());
+ executor.shutdown();
}
- }, MoreExecutors.directExecutor());
- }
-
- private void maybeSnapshotReplicas(UUID parentSession, String keyspace, List<RepairSessionResult> results)
- {
- if (!DatabaseDescriptor.snapshotOnRepairedDataMismatch())
- return;
-
- try
- {
- Set<String> mismatchingTables = new HashSet<>();
- Set<InetAddressAndPort> nodes = new HashSet<>();
- for (RepairSessionResult sessionResult : results)
- {
- for (RepairResult repairResult : emptyIfNull(sessionResult.repairJobResults))
- {
- for (SyncStat stat : emptyIfNull(repairResult.stats))
- {
- if (stat.numberOfDifferences > 0)
- mismatchingTables.add(repairResult.desc.columnFamily);
- // snapshot all replicas, even if they don't have any differences
- nodes.add(stat.nodes.coordinator);
- nodes.add(stat.nodes.peer);
- }
- }
- }
-
- String snapshotName = DiagnosticSnapshotService.getSnapshotName(DiagnosticSnapshotService.REPAIRED_DATA_MISMATCH_SNAPSHOT_PREFIX);
- for (String table : mismatchingTables)
- {
- // we can just check snapshot existence locally since the repair coordinator is always a replica (unlike in the read case)
- if (!Keyspace.open(keyspace).getColumnFamilyStore(table).snapshotExists(snapshotName))
- {
- logger.info("{} Snapshotting {}.{} for preview repair mismatch with tag {} on instances {}",
- options.getPreviewKind().logPrefix(parentSession),
- keyspace, table, snapshotName, nodes);
- DiagnosticSnapshotService.repairedDataMismatch(Keyspace.open(keyspace).getColumnFamilyStore(table).metadata(), nodes);
- }
- else
- {
- logger.info("{} Not snapshotting {}.{} - snapshot {} exists",
- options.getPreviewKind().logPrefix(parentSession),
- keyspace, table, snapshotName);
- }
- }
- }
- catch (Exception e)
- {
- logger.error("{} Failed snapshotting replicas", options.getPreviewKind().logPrefix(parentSession), e);
- }
+ });
}
- private static <T> Iterable<T> emptyIfNull(Iterable<T> iter)
+ private ExecutorPlus createExecutor()
{
- if (iter == null)
- return Collections.emptyList();
- return iter;
- }
-
- private ListenableFuture<List<RepairSessionResult>> submitRepairSessions(UUID parentSession,
- boolean isIncremental,
- ListeningExecutorService executor,
- List<CommonRange> commonRanges,
- String... cfnames)
- {
- List<ListenableFuture<RepairSessionResult>> futures = new ArrayList<>(options.getRanges().size());
-
- for (CommonRange commonRange : commonRanges)
- {
- logger.info("Starting RepairSession for {}", commonRange);
- RepairSession session = ActiveRepairService.instance.submitRepairSession(parentSession,
- commonRange,
- keyspace,
- options.getParallelism(),
- isIncremental,
- options.isPullRepair(),
- options.getPreviewKind(),
- options.optimiseStreams(),
- executor,
- cfnames);
- if (session == null)
- continue;
- Futures.addCallback(session, new RepairSessionCallback(session), MoreExecutors.directExecutor());
- futures.add(session);
- }
- return Futures.successfulAsList(futures);
- }
-
- private ListeningExecutorService createExecutor()
- {
- return MoreExecutors.listeningDecorator(new JMXEnabledThreadPoolExecutor(options.getJobThreads(),
- Integer.MAX_VALUE,
- TimeUnit.SECONDS,
- new LinkedBlockingQueue<>(),
- new NamedThreadFactory("Repair#" + cmd),
- "internal"));
- }
-
- private class RepairSessionCallback implements FutureCallback<RepairSessionResult>
- {
- private final RepairSession session;
-
- public RepairSessionCallback(RepairSession session)
- {
- this.session = session;
- }
-
- public void onSuccess(RepairSessionResult result)
- {
- String message = String.format("Repair session %s for range %s finished", session.getId(),
- session.ranges().toString());
- logger.info(message);
- fireProgressEvent(new ProgressEvent(ProgressEventType.PROGRESS,
- progressCounter.incrementAndGet(),
- totalProgress,
- message));
- }
-
- public void onFailure(Throwable t)
- {
- String message = String.format("Repair session %s for range %s failed with error %s",
- session.getId(), session.ranges().toString(), t.getMessage());
- notifyError(new RuntimeException(message, t));
- }
- }
-
- private class RepairCompleteCallback implements FutureCallback<Object>
- {
- final UUID parentSession;
- final Collection<Range<Token>> successfulRanges;
- final Set<InetAddressAndPort> preparedEndpoints;
- final long startTime;
- final TraceState traceState;
- final AtomicBoolean hasFailure;
- final ExecutorService executor;
-
- public RepairCompleteCallback(UUID parentSession,
- Collection<Range<Token>> successfulRanges,
- Set<InetAddressAndPort> preparedEndpoints,
- long startTime,
- TraceState traceState,
- AtomicBoolean hasFailure,
- ExecutorService executor)
- {
- this.parentSession = parentSession;
- this.successfulRanges = successfulRanges;
- this.preparedEndpoints = preparedEndpoints;
- this.startTime = startTime;
- this.traceState = traceState;
- this.hasFailure = hasFailure;
- this.executor = executor;
- }
-
- public void onSuccess(Object result)
- {
- maybeStoreParentRepairSuccess(successfulRanges);
- if (hasFailure.get())
- {
- fail(null);
- }
- else
- {
- success("Repair completed successfully");
- ActiveRepairService.instance.cleanUp(parentSession, preparedEndpoints);
- }
- executor.shutdown();
- }
-
- public void onFailure(Throwable t)
- {
- notifyError(t);
- fail(t.getMessage());
- executor.shutdown();
- }
+ return executorFactory()
+ .localAware()
+ .withJmxInternal()
+ .pooled("Repair#" + cmd, options.getJobThreads());
}
private static void addRangeToNeighbors(List<CommonRange> neighborRangeList, Range<Token> range, EndpointsForRange neighbors)
diff --cc src/java/org/apache/cassandra/repair/RepairSession.java
index bfd6a7e,692cdcf..bb489f2
--- a/src/java/org/apache/cassandra/repair/RepairSession.java
+++ b/src/java/org/apache/cassandra/repair/RepairSession.java
@@@ -18,16 -18,10 +18,16 @@@
package org.apache.cassandra.repair;
import java.io.IOException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
- import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.common.annotations.VisibleForTesting;
@@@ -371,9 -339,25 +372,25 @@@ public class RepairSession extends Asyn
*/
public void forceShutdown(Throwable reason)
{
- setException(reason);
+ tryFailure(reason);
- taskExecutor.shutdownNow();
+ taskExecutor.shutdown();
terminate();
+ awaitTaskExecutorTermination();
+ }
+
+ private void awaitTaskExecutorTermination()
+ {
+ try
+ {
+ if (taskExecutor.awaitTermination(30, TimeUnit.SECONDS))
+ logger.debug("{} session task executor shut down gracefully", previewKind.logPrefix(getId()));
+ else
+ logger.warn("{} session task executor unable to shut down gracefully", previewKind.logPrefix(getId()));
+ }
+ catch (InterruptedException e)
+ {
+ Thread.currentThread().interrupt();
+ }
}
public void onRemove(InetAddressAndPort endpoint)
diff --cc src/java/org/apache/cassandra/repair/SnapshotTask.java
index b75d889,46532fb5..8c65fb3
--- a/src/java/org/apache/cassandra/repair/SnapshotTask.java
+++ b/src/java/org/apache/cassandra/repair/SnapshotTask.java
@@@ -53,7 -54,7 +53,7 @@@ public class SnapshotTask extends Async
/**
* Callback for snapshot request. Run on INTERNAL_RESPONSE stage.
*/
-- static class SnapshotCallback implements RequestCallback
++ static class SnapshotCallback implements RequestCallback<InetAddressAndPort>
{
final SnapshotTask task;
@@@ -82,8 -83,7 +82,7 @@@
@Override
public void onFailure(InetAddressAndPort from, RequestFailureReason failureReason)
{
- //listener.failedSnapshot();
- task.setException(new RuntimeException("Could not create snapshot at " + from));
+ task.tryFailure(new RuntimeException("Could not create snapshot at " + from));
}
}
}
diff --cc src/java/org/apache/cassandra/repair/SyncTask.java
index 733203a,fe9f09e..e254d93
--- a/src/java/org/apache/cassandra/repair/SyncTask.java
+++ b/src/java/org/apache/cassandra/repair/SyncTask.java
@@@ -35,11 -35,9 +35,11 @@@ import org.apache.cassandra.locator.Ine
import org.apache.cassandra.streaming.PreviewKind;
import org.apache.cassandra.tracing.Tracing;
-public abstract class SyncTask extends AbstractFuture<SyncStat> implements Runnable
+import static org.apache.cassandra.utils.Clock.Global.currentTimeMillis;
+
+public abstract class SyncTask extends AsyncFuture<SyncStat> implements Runnable
{
- private static Logger logger = LoggerFactory.getLogger(SyncTask.class);
+ private static final Logger logger = LoggerFactory.getLogger(SyncTask.class);
protected final RepairJobDesc desc;
@VisibleForTesting
@@@ -99,6 -97,8 +99,8 @@@
protected void finished()
{
if (startTime != Long.MIN_VALUE)
- Keyspace.open(desc.keyspace).getColumnFamilyStore(desc.columnFamily).metric.repairSyncTime.update(System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
+ Keyspace.open(desc.keyspace).getColumnFamilyStore(desc.columnFamily).metric.repairSyncTime.update(currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}
+
+ public void abort() {}
}
diff --cc src/java/org/apache/cassandra/service/ActiveRepairService.java
index 9269e0f,4a990f6..7f2ddf1
--- a/src/java/org/apache/cassandra/service/ActiveRepairService.java
+++ b/src/java/org/apache/cassandra/service/ActiveRepairService.java
@@@ -943,73 -898,9 +943,79 @@@ public class ActiveRepairService implem
return parentRepairSessions.size();
}
+ @VisibleForTesting
+ public int sessionCount()
+ {
+ return sessions.size();
+ }
++
+ public Future<?> repairPaxosForTopologyChange(String ksName, Collection<Range<Token>> ranges, String reason)
+ {
+ if (!paxosRepairEnabled())
+ {
+ logger.warn("Not running paxos repair for topology change because paxos repair has been disabled");
+ return ImmediateFuture.success(null);
+ }
+
+ if (ranges.isEmpty())
+ {
+ logger.warn("Not running paxos repair for topology change because there are no ranges to repair");
+ return ImmediateFuture.success(null);
+ }
+ List<TableMetadata> tables = Lists.newArrayList(Schema.instance.getKeyspaceMetadata(ksName).tables);
+ List<Future<Void>> futures = new ArrayList<>(ranges.size() * tables.size());
+ Keyspace keyspace = Keyspace.open(ksName);
+ AbstractReplicationStrategy replication = keyspace.getReplicationStrategy();
+ for (Range<Token> range: ranges)
+ {
+ for (TableMetadata table : tables)
+ {
+ Set<InetAddressAndPort> endpoints = replication.getNaturalReplicas(range.right).filter(FailureDetector.isReplicaAlive).endpoints();
+ if (!PaxosRepair.hasSufficientLiveNodesForTopologyChange(keyspace, range, endpoints))
+ {
+ Set<InetAddressAndPort> downEndpoints = replication.getNaturalReplicas(range.right).filter(e -> !endpoints.contains(e)).endpoints();
+ downEndpoints.removeAll(endpoints);
+
+ throw new RuntimeException(String.format("Insufficient live nodes to repair paxos for %s in %s for %s.\n" +
+ "There must be enough live nodes to satisfy EACH_QUORUM, but the following nodes are down: %s\n" +
+ "This check can be skipped by setting either the yaml property skip_paxos_repair_on_topology_change or " +
+ "the system property cassandra.skip_paxos_repair_on_topology_change to false. The jmx property " +
+ "StorageService.SkipPaxosRepairOnTopologyChange can also be set to false to temporarily disable without " +
+ "restarting the node\n" +
+ "Individual keyspaces can be skipped with the yaml property skip_paxos_repair_on_topology_change_keyspaces, the" +
+ "system property cassandra.skip_paxos_repair_on_topology_change_keyspaces, or temporarily with the jmx" +
+ "property StorageService.SkipPaxosRepairOnTopologyChangeKeyspaces\n" +
+ "Skipping this check can lead to paxos correctness issues",
+ range, ksName, reason, downEndpoints));
+ }
+ EndpointsForToken pending = StorageService.instance.getTokenMetadata().pendingEndpointsForToken(range.right, ksName);
+ if (pending.size() > 1 && !Boolean.getBoolean("cassandra.paxos_repair_allow_multiple_pending_unsafe"))
+ {
+ throw new RuntimeException(String.format("Cannot begin paxos auto repair for %s in %s.%s, multiple pending endpoints exist for range (%s). " +
+ "Set -Dcassandra.paxos_repair_allow_multiple_pending_unsafe=true to skip this check",
+ range, table.keyspace, table.name, pending));
+
+ }
+ Future<Void> future = PaxosCleanup.cleanup(endpoints, table, Collections.singleton(range), false, repairCommandExecutor());
+ futures.add(future);
+ }
+ }
+
+ return FutureCombiner.allOf(futures);
+ }
+
+ public int getPaxosRepairParallelism()
+ {
+ return DatabaseDescriptor.getPaxosRepairParallelism();
+ }
+
+ public void setPaxosRepairParallelism(int v)
+ {
+ DatabaseDescriptor.setPaxosRepairParallelism(v);
+ }
+
+ public void shutdownNowAndWait(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException
+ {
+ ExecutorUtils.shutdownNowAndWait(timeout, unit, clearSnapshotExecutor);
+ }
}
diff --cc src/java/org/apache/cassandra/streaming/StreamCoordinator.java
index ca238ba,8bcf54e..ad292517
--- a/src/java/org/apache/cassandra/streaming/StreamCoordinator.java
+++ b/src/java/org/apache/cassandra/streaming/StreamCoordinator.java
@@@ -17,8 -17,8 +17,9 @@@
*/
package org.apache.cassandra.streaming;
+import java.net.InetSocketAddress;
import java.util.*;
+ import java.util.concurrent.ConcurrentHashMap;
import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
@@@ -43,7 -40,7 +44,7 @@@ public class StreamCoordinato
private final boolean connectSequentially;
- private final Map<InetSocketAddress, HostStreamingData> peerSessions = new HashMap<>();
- private final Map<InetAddressAndPort, HostStreamingData> peerSessions = new ConcurrentHashMap<>();
++ private final Map<InetSocketAddress, HostStreamingData> peerSessions = new ConcurrentHashMap<>();
private final StreamOperation streamOperation;
private final int connectionsPerHost;
private final boolean follower;
diff --cc src/java/org/apache/cassandra/streaming/StreamResultFuture.java
index d54b607,3b8ffdc..22af238
--- a/src/java/org/apache/cassandra/streaming/StreamResultFuture.java
+++ b/src/java/org/apache/cassandra/streaming/StreamResultFuture.java
@@@ -145,9 -143,10 +145,10 @@@ public final class StreamResultFuture e
session.init(this);
}
+ @SuppressWarnings("UnstableApiUsage")
public void addEventListener(StreamEventHandler listener)
{
- Futures.addCallback(this, listener, MoreExecutors.directExecutor());
+ addCallback(listener);
eventListeners.add(listener);
}
@@@ -228,8 -218,13 +229,13 @@@
if (finalState.hasFailedSession())
{
logger.warn("[Stream #{}] Stream failed", planId);
- setException(new StreamException(finalState, "Stream failed"));
+ tryFailure(new StreamException(finalState, "Stream failed"));
}
+ else if (finalState.hasAbortedSession())
+ {
+ logger.info("[Stream #{}] Stream aborted", planId);
- set(finalState);
++ trySuccess(finalState);
+ }
else
{
logger.info("[Stream #{}] All sessions completed", planId);
diff --cc src/java/org/apache/cassandra/streaming/StreamSession.java
index 5ac783b,9a34285..9c1aa76
--- a/src/java/org/apache/cassandra/streaming/StreamSession.java
+++ b/src/java/org/apache/cassandra/streaming/StreamSession.java
@@@ -19,19 -19,12 +19,27 @@@ package org.apache.cassandra.streaming
import java.io.EOFException;
import java.net.SocketTimeoutException;
-import java.util.*;
-import java.util.concurrent.*;
+import java.nio.channels.ClosedChannelException;
- import java.util.*;
++import java.util.ArrayList;
++import java.util.Collection;
++import java.util.HashMap;
++import java.util.HashSet;
++import java.util.List;
++import java.util.Map;
++import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
--import com.google.common.collect.*;
++import com.google.common.collect.Iterables;
++import com.google.common.collect.Lists;
++import com.google.common.collect.Sets;
+import io.netty.channel.Channel;
+import io.netty.util.concurrent.Future; //checkstyle: permit this import
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.locator.RangesAtEndpoint;
@@@ -180,29 -172,29 +188,29 @@@ public class StreamSession implements I
private boolean maybeCompleted = false;
private Future<?> closeFuture;
- private final UUID pendingRepair;
+ private final TimeUUID pendingRepair;
private final PreviewKind previewKind;
- /**
- * State Transition:
- *
- * <pre>
- * +------------------+----------> FAILED <--------------------+
- * | | ^ |
- * | | | initiator |
- * INITIALIZED --> PREPARING --> STREAMING ------------> WAIT_COMPLETE ----> COMPLETED
- * | | | ^ ^
- * | | | follower | |
- * | | +-------------------------)-----------------+
- * | | | |
- * | | if preview | |
- * | +----------------------------------------+ |
- * | nothing to request or to transfer |
- * +-----------------------------------------------------------------------------+
- * nothing to request or to transfer
- *
- * </pre>
- */
+ /**
+ * State Transition:
+ *
+ * <pre>
+ * +------------------+-----> FAILED | ABORTED <---------------+
+ * | | ^ |
+ * | | | initiator |
+ * INITIALIZED --> PREPARING --> STREAMING ------------> WAIT_COMPLETE ----> COMPLETED
+ * | | | ^ ^
+ * | | | follower | |
+ * | | +-------------------------)-----------------+
+ * | | | |
+ * | | if preview | |
+ * | +----------------------------------------+ |
+ * | nothing to request or to transfer |
+ * +-----------------------------------------------------------------------------+
+ * nothing to request or to transfer
+ *
+ * </pre>
+ */
public enum State
{
INITIALIZED(false),
@@@ -635,12 -629,11 +644,12 @@@
* after completion or because the peer was down, otherwise sends a {@link SessionFailedMessage} and closes
* the session as {@link State#FAILED}.
*/
- public synchronized Future onError(Throwable e)
+ public synchronized Future<?> onError(Throwable e)
{
- boolean isEofException = e instanceof EOFException;
+ boolean isEofException = e instanceof EOFException || e instanceof ClosedChannelException;
if (isEofException)
{
+ State state = this.state;
if (state.finalState)
{
logger.debug("[Stream #{}] Socket closed after session completed with state {}", planId(), state);
@@@ -1075,33 -1037,20 +1084,50 @@@
public void onClose(InetAddressAndPort from);
}
+ public static String createLogTag(StreamSession session)
+ {
+ return createLogTag(session, (Object) null);
+ }
+
+ public static String createLogTag(StreamSession session, StreamingChannel channel)
+ {
+ return createLogTag(session, channel == null ? null : channel.id());
+ }
+
+ public static String createLogTag(StreamSession session, Channel channel)
+ {
+ return createLogTag(session, channel == null ? null : channel.id());
+ }
+
+ public static String createLogTag(StreamSession session, Object channelId)
+ {
+ StringBuilder sb = new StringBuilder(64);
+ sb.append("[Stream");
+
+ if (session != null)
+ sb.append(" #").append(session.planId());
+
+ if (channelId != null)
+ sb.append(" channel: ").append(channelId);
+
+ sb.append(']');
+ return sb.toString();
+ }
++
+ public synchronized void abort()
+ {
+ logger.info("[Stream #{}] Aborting stream session with peer {}...", planId(), peer);
+
- if (getMessageSender().connected())
- getMessageSender().sendMessage(new SessionFailedMessage());
++ if (channel.connected())
++ channel.sendControlMessage(new SessionFailedMessage());
+
+ try
+ {
+ closeSession(State.ABORTED);
+ }
+ catch (Exception e)
+ {
+ logger.error("[Stream #{}] Error aborting stream session with peer {}", planId(), peer);
+ }
+ }
}
diff --cc src/java/org/apache/cassandra/streaming/StreamState.java
index 55e50e6,1b7c042..88eb76d
--- a/src/java/org/apache/cassandra/streaming/StreamState.java
+++ b/src/java/org/apache/cassandra/streaming/StreamState.java
@@@ -20,8 -20,8 +20,7 @@@ package org.apache.cassandra.streaming
import java.io.Serializable;
import java.util.List;
import java.util.Set;
-import java.util.UUID;
- import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
diff --cc test/distributed/org/apache/cassandra/distributed/test/RepairErrorsTest.java
index b5363c4,8b77b3f..e771e2e
--- a/test/distributed/org/apache/cassandra/distributed/test/RepairErrorsTest.java
+++ b/test/distributed/org/apache/cassandra/distributed/test/RepairErrorsTest.java
@@@ -18,114 -18,148 +18,221 @@@
package org.apache.cassandra.distributed.test;
+import java.io.IOException;
+import java.util.Collection;
- import java.util.UUID;
-
- import org.assertj.core.api.Assertions;
- import org.junit.Test;
+ import java.util.concurrent.Callable;
-import java.util.concurrent.Future;
+ import java.util.concurrent.TimeUnit;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
+ import net.bytebuddy.implementation.bind.annotation.SuperCall;
++import org.assertj.core.api.Assertions;
+ import org.junit.Test;
+
-import org.apache.cassandra.concurrent.DebuggableThreadPoolExecutor;
+ import org.apache.cassandra.db.SystemKeyspace;
+import org.apache.cassandra.db.compaction.CompactionInterruptedException;
+import org.apache.cassandra.db.compaction.CompactionIterator;
+import org.apache.cassandra.db.compaction.CompactionManager;
+import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
+ import org.apache.cassandra.distributed.api.NodeToolResult;
+import org.apache.cassandra.io.sstable.format.SSTableReader;
+ import org.apache.cassandra.locator.InetAddressAndPort;
-import org.apache.cassandra.service.ActiveRepairService;
+import org.apache.cassandra.locator.RangesAtEndpoint;
+ import org.apache.cassandra.streaming.StreamSession;
++import org.apache.cassandra.service.ActiveRepairService;
++import org.apache.cassandra.utils.TimeUUID;
import static net.bytebuddy.matcher.ElementMatchers.named;
-import static net.bytebuddy.matcher.ElementMatchers.takesArguments;
+ import static org.junit.Assert.assertEquals;
+ import static org.junit.Assert.assertTrue;
+
import static org.apache.cassandra.distributed.api.Feature.GOSSIP;
import static org.apache.cassandra.distributed.api.Feature.NETWORK;
- import static org.junit.Assert.assertTrue;
public class RepairErrorsTest extends TestBaseImpl
{
+ @Test
+ public void testRemoteValidationFailure() throws IOException
+ {
+ Cluster.Builder builder = Cluster.build(2)
+ .withConfig(config -> config.with(GOSSIP).with(NETWORK))
+ .withInstanceInitializer(ByteBuddyHelper::install);
+ try (Cluster cluster = builder.createWithoutStarting())
+ {
+ cluster.setUncaughtExceptionsFilter((i, throwable) -> {
+ if (i == 2)
+ return throwable.getMessage() != null && throwable.getMessage().contains("IGNORE");
+ return false;
+ });
+
+ cluster.startup();
+ init(cluster);
+
+ cluster.schemaChange("create table "+KEYSPACE+".tbl (id int primary key, x int)");
+ for (int i = 0; i < 10; i++)
+ cluster.coordinator(1).execute("insert into "+KEYSPACE+".tbl (id, x) VALUES (?,?)", ConsistencyLevel.ALL, i, i);
+ cluster.forEach(i -> i.flush(KEYSPACE));
+ long mark = cluster.get(1).logs().mark();
+ cluster.forEach(i -> i.nodetoolResult("repair", "--full").asserts().failure());
+ Assertions.assertThat(cluster.get(1).logs().grep(mark, "^ERROR").getResult()).isEmpty();
+ }
+ }
+
+ @SuppressWarnings("Convert2MethodRef")
+ @Test
+ public void testRemoteSyncFailure() throws Exception
+ {
+ try (Cluster cluster = init(Cluster.build(3)
+ .withConfig(config -> config.with(GOSSIP)
+ .with(NETWORK)
+ .set("disk_failure_policy", "stop")
+ .set("disk_access_mode", "mmap_index_only"))
+ .withInstanceInitializer(ByteBuddyHelper::installStreamPlanExecutionFailure).start()))
+ {
+ cluster.schemaChange("create table " + KEYSPACE + ".tbl (id int primary key, x int)");
+
+ // On repair, this data layout will require two (local) syncs from node 1 and one remote sync from node 2:
+ cluster.get(1).executeInternal("insert into " + KEYSPACE + ".tbl (id, x) VALUES (?,?)", 1, 1);
+ cluster.get(2).executeInternal("insert into " + KEYSPACE + ".tbl (id, x) VALUES (?,?)", 2, 2);
+ cluster.get(3).executeInternal("insert into " + KEYSPACE + ".tbl (id, x) VALUES (?,?)", 3, 3);
+ cluster.forEach(i -> i.flush(KEYSPACE));
+
+ // Flush system.peers_v2, or there won't be any SSTables...
+ cluster.forEach(i -> i.flush("system"));
+
+ // The remote sync started from node 2 will fail on plan execution and propagate the error...
+ NodeToolResult result = cluster.get(1).nodetoolResult("repair", KEYSPACE);
+ result.asserts().failure().errorContains("Sync failed between /127.0.0.2:7012 and /127.0.0.3:7012");
+
+ // Before CASSANDRA-17466 added an abort mechanism for local sync tasks and switched the repair task
+ // executor to shut down without interrupting its threads, we could trigger the disk failure policy, as
+ // interruption could accidentally close shared channels in the middle of a blocking operation. To see
+ // this, simply revert those changes in RepairJob (aborting sync tasks) and RepairSession (shutdown()
+ // rather than shutdownNow() on failure).
+ assertTrue(cluster.get(1).logs().grep("Stopping transports as disk_failure_policy is stop").getResult().isEmpty());
+ assertTrue(cluster.get(1).logs().grep("FSReadError").getResult().isEmpty());
+ assertTrue(cluster.get(1).logs().grep("ClosedByInterruptException").getResult().isEmpty());
+
+ // Make sync unnecessary, and repair should succeed:
+ cluster.coordinator(1).execute("insert into " + KEYSPACE + ".tbl (id, x) VALUES (?,?)", ConsistencyLevel.ALL, 1, 1);
+ cluster.coordinator(1).execute("insert into " + KEYSPACE + ".tbl (id, x) VALUES (?,?)", ConsistencyLevel.ALL, 2, 2);
+ cluster.coordinator(1).execute("insert into " + KEYSPACE + ".tbl (id, x) VALUES (?,?)", ConsistencyLevel.ALL, 3, 3);
+ cluster.forEach(i -> i.flush(KEYSPACE));
+ result = cluster.get(1).nodetoolResult("repair", KEYSPACE);
+ result.asserts().success();
+
+ // Make sure we've cleaned up sessions and parent sessions:
+ Integer parents = cluster.get(1).callOnInstance(() -> ActiveRepairService.instance.parentRepairSessionCount());
+ assertEquals(0, parents.intValue());
+ Integer sessions = cluster.get(1).callOnInstance(() -> ActiveRepairService.instance.sessionCount());
+ assertEquals(0, sessions.intValue());
+ }
+ }
+
+ @Test
+ public void testNoSuchRepairSessionAnticompaction() throws IOException
+ {
+ try (Cluster cluster = init(Cluster.build(2)
+ .withConfig(config -> config.with(GOSSIP).with(NETWORK))
+ .withInstanceInitializer(ByteBuddyHelper::installACNoSuchRepairSession)
+ .start()))
+ {
+ cluster.schemaChange("create table "+KEYSPACE+".tbl (id int primary key, x int)");
+ for (int i = 0; i < 10; i++)
+ cluster.coordinator(1).execute("insert into "+KEYSPACE+".tbl (id, x) VALUES (?,?)", ConsistencyLevel.ALL, i, i);
+ cluster.forEach(i -> i.flush(KEYSPACE));
+ long mark = cluster.get(1).logs().mark();
+ cluster.forEach(i -> i.nodetoolResult("repair", KEYSPACE).asserts().failure());
+ assertTrue(cluster.get(1).logs().grep(mark, "^ERROR").getResult().isEmpty());
+ }
+ }
+
public static class ByteBuddyHelper
{
+ public static void install(ClassLoader cl, int nodeNumber)
+ {
+ if (nodeNumber == 2)
+ {
+ new ByteBuddy().redefine(CompactionIterator.class)
+ .method(named("next"))
+ .intercept(MethodDelegation.to(ByteBuddyHelper.class))
+ .make()
+ .load(cl, ClassLoadingStrategy.Default.INJECTION);
+ }
+ }
+
+ public static void installACNoSuchRepairSession(ClassLoader cl, int nodeNumber)
+ {
+ if (nodeNumber == 2)
+ {
+ new ByteBuddy().redefine(CompactionManager.class)
+ .method(named("validateSSTableBoundsForAnticompaction"))
+ .intercept(MethodDelegation.to(ByteBuddyHelper.class))
+ .make()
+ .load(cl, ClassLoadingStrategy.Default.INJECTION);
+ }
+ }
++
+ public static void installStreamPlanExecutionFailure(ClassLoader cl, int nodeNumber)
+ {
+ if (nodeNumber == 2)
+ {
+ new ByteBuddy().rebase(StreamSession.class)
+ .method(named("onInitializationComplete"))
+ .intercept(MethodDelegation.to(ByteBuddyHelper.class))
+ .make()
+ .load(cl, ClassLoadingStrategy.Default.INJECTION);
+ }
+
+ if (nodeNumber == 1)
+ {
+ new ByteBuddy().rebase(SystemKeyspace.class)
+ .method(named("getPreferredIP"))
+ .intercept(MethodDelegation.to(ByteBuddyHelper.class))
+ .make()
+ .load(cl, ClassLoadingStrategy.Default.INJECTION);
-
- new ByteBuddy().rebase(DebuggableThreadPoolExecutor.class)
- .method(named("extractThrowable").and(takesArguments(Future.class)))
- .intercept(MethodDelegation.to(ByteBuddyHelper.class))
- .make()
- .load(cl, ClassLoadingStrategy.Default.INJECTION);
+ }
+ }
+ public static UnfilteredRowIterator next()
+ {
+ throw new RuntimeException("IGNORE");
+ }
+
+ @SuppressWarnings("unused")
- public static void validateSSTableBoundsForAnticompaction(UUID sessionID,
++ public static void validateSSTableBoundsForAnticompaction(TimeUUID sessionID,
+ Collection<SSTableReader> sstables,
+ RangesAtEndpoint ranges)
+ {
+ throw new CompactionInterruptedException(String.valueOf(sessionID));
+ }
++
+ @SuppressWarnings("unused")
+ public static void onInitializationComplete()
+ {
+ throw new RuntimeException("Failing stream session initialization from test!");
+ }
+
+ @SuppressWarnings("unused")
+ public static InetAddressAndPort getPreferredIP(InetAddressAndPort ep, @SuperCall Callable<InetAddressAndPort> zuper) throws Exception
+ {
+ if (Thread.currentThread().getName().contains("RepairJobTask"))
+ {
+ try
+ {
- TimeUnit.SECONDS.sleep(60);
++ TimeUnit.SECONDS.sleep(10);
+ }
+ catch (InterruptedException e)
+ {
+ // Leave the interrupt flag intact for the ChannelProxy downstream...
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ return zuper.call();
+ }
-
- @SuppressWarnings({"unused", "ResultOfMethodCallIgnored"})
- public static Throwable extractThrowable(Future<?> future, @SuperCall Callable<Throwable> zuper) throws Exception
- {
- if (Thread.currentThread().getName().contains("RepairJobTask"))
- // Clear the interrupt flag so the FSReadError is propagated correctly in DebuggableThreadPoolExecutor:
- Thread.interrupted();
-
- return zuper.call();
- }
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org