Skip to content

Add retention leases replication tests #38857

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3162,4 +3162,8 @@ public void advanceMaxSeqNoOfUpdatesOrDeletes(long seqNo) {
public void verifyShardBeforeIndexClosing() throws IllegalStateException {
getEngine().verifyEngineBeforeIndexClosing();
}

RetentionLeaseSyncer getRetentionLeaseSyncer() {
return retentionLeaseSyncer;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.replication;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.seqno.RetentionLease;
import org.elasticsearch.index.seqno.RetentionLeaseSyncAction;
import org.elasticsearch.index.seqno.RetentionLeases;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShardId;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;

public class RetentionLeasesReplicationTests extends ESIndexLevelReplicationTestCase {

public void testSimpleSyncRetentionLeases() throws Exception {
Settings settings = Settings.builder().put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).build();
try (ReplicationGroup group = createGroup(between(0, 2), settings)) {
group.startAll();
List<RetentionLease> leases = new ArrayList<>();
int iterations = between(1, 100);
CountDownLatch latch = new CountDownLatch(iterations);
for (int i = 0; i < iterations; i++) {
if (leases.isEmpty() == false && rarely()) {
RetentionLease leaseToRemove = randomFrom(leases);
leases.remove(leaseToRemove);
group.removeRetentionLease(leaseToRemove.id(), ActionListener.wrap(latch::countDown));
} else {
RetentionLease newLease = group.addRetentionLease(Integer.toString(i), randomNonNegativeLong(), "test-" + i,
ActionListener.wrap(latch::countDown));
leases.add(newLease);
}
}
RetentionLeases leasesOnPrimary = group.getPrimary().getRetentionLeases();
assertThat(leasesOnPrimary.version(), equalTo((long) iterations));
assertThat(leasesOnPrimary.primaryTerm(), equalTo(group.getPrimary().getOperationPrimaryTerm()));
assertThat(leasesOnPrimary.leases(), containsInAnyOrder(leases.toArray(new RetentionLease[0])));
latch.await();
for (IndexShard replica : group.getReplicas()) {
assertThat(replica.getRetentionLeases(), equalTo(leasesOnPrimary));
}
}
}

public void testOutOfOrderRetentionLeasesRequests() throws Exception {
Settings settings = Settings.builder().put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).build();
int numberOfReplicas = between(1, 2);
IndexMetaData indexMetaData = buildIndexMetaData(numberOfReplicas, settings, indexMapping);
try (ReplicationGroup group = new ReplicationGroup(indexMetaData) {
@Override
protected void syncRetentionLeases(ShardId shardId, RetentionLeases leases, ActionListener<ReplicationResponse> listener) {
listener.onResponse(new SyncRetentionLeasesResponse(new RetentionLeaseSyncAction.Request(shardId, leases)));
}
}) {
group.startAll();
int numLeases = between(1, 10);
List<RetentionLeaseSyncAction.Request> requests = new ArrayList<>();
for (int i = 0; i < numLeases; i++) {
PlainActionFuture<ReplicationResponse> future = new PlainActionFuture<>();
group.addRetentionLease(Integer.toString(i), randomNonNegativeLong(), "test-" + i, future);
requests.add(((SyncRetentionLeasesResponse) future.actionGet()).syncRequest);
}
RetentionLeases leasesOnPrimary = group.getPrimary().getRetentionLeases();
for (IndexShard replica : group.getReplicas()) {
Randomness.shuffle(requests);
requests.forEach(request -> group.executeRetentionLeasesSyncRequestOnReplica(request, replica));
assertThat(replica.getRetentionLeases(), equalTo(leasesOnPrimary));
}
}
}

public void testSyncRetentionLeasesWithPrimaryPromotion() throws Exception {
Settings settings = Settings.builder().put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true).build();
int numberOfReplicas = between(2, 4);
IndexMetaData indexMetaData = buildIndexMetaData(numberOfReplicas, settings, indexMapping);
try (ReplicationGroup group = new ReplicationGroup(indexMetaData) {
@Override
protected void syncRetentionLeases(ShardId shardId, RetentionLeases leases, ActionListener<ReplicationResponse> listener) {
listener.onResponse(new SyncRetentionLeasesResponse(new RetentionLeaseSyncAction.Request(shardId, leases)));
}
}) {
group.startAll();
int numLeases = between(1, 100);
IndexShard newPrimary = randomFrom(group.getReplicas());
RetentionLeases latestRetentionLeasesOnNewPrimary = RetentionLeases.EMPTY;
for (int i = 0; i < numLeases; i++) {
PlainActionFuture<ReplicationResponse> addLeaseFuture = new PlainActionFuture<>();
group.addRetentionLease(Integer.toString(i), randomNonNegativeLong(), "test-" + i, addLeaseFuture);
RetentionLeaseSyncAction.Request request = ((SyncRetentionLeasesResponse) addLeaseFuture.actionGet()).syncRequest;
for (IndexShard replica : randomSubsetOf(group.getReplicas())) {
group.executeRetentionLeasesSyncRequestOnReplica(request, replica);
if (newPrimary == replica) {
latestRetentionLeasesOnNewPrimary = request.getRetentionLeases();
}
}
}
group.promoteReplicaToPrimary(newPrimary).get();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discuss: should we align the retention-leases when a new primary is promoted?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Under what circumstances can the new primary not hold an up-to-date set of leases already? It might perhaps be missing some renewals but I think that's ok.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are adding two new leases to the old primary: L1 and L2. L1 was synced to replica r1; L2 was synced to r2, but the old primary crashed before two leases are properly synced to all two replicas. If any replica is promoted, then the retention leases between copies are not aligned.

Copy link
Contributor

@DaveCTurner DaveCTurner Feb 19, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We sync by copying all the leases from the primary to its replicas, so I don't follow how r2 could receive L2 without also receiving L1 (assuming they were added in this order).

However, I think I do see a potential problem:

  • primary A shares a lease with one replica B, but not to another replica C
  • A crashes
  • C discards some history that the lease would have retained
  • B is promoted to primary and shares its lease with C
  • C cannot accept this lease since it has already discarded this history

I think we can prevent this, with peer-recovery retention leases, by insisting that leases do not "go backwards", i.e. they only retain history that is already being retained by another lease. This would mean that C could not discard the history in the situation above because it must already hold a different lease that retains that history.

// we need to make changes to retention leases to sync it to replicas
// since we don't sync retention leases when promoting a new primary.
PlainActionFuture<ReplicationResponse> newLeaseFuture = new PlainActionFuture<>();
group.addRetentionLease("new-lease-after-promotion", randomNonNegativeLong(), "test", newLeaseFuture);
RetentionLeases leasesOnPrimary = group.getPrimary().getRetentionLeases();
assertThat(leasesOnPrimary.primaryTerm(), equalTo(group.getPrimary().getOperationPrimaryTerm()));
assertThat(leasesOnPrimary.version(), equalTo(latestRetentionLeasesOnNewPrimary.version() + 1L));
assertThat(leasesOnPrimary.leases(), hasSize(latestRetentionLeasesOnNewPrimary.leases().size() + 1));
RetentionLeaseSyncAction.Request request = ((SyncRetentionLeasesResponse) newLeaseFuture.actionGet()).syncRequest;
for (IndexShard replica : group.getReplicas()) {
group.executeRetentionLeasesSyncRequestOnReplica(request, replica);
}
for (IndexShard replica : group.getReplicas()) {
assertThat(replica.getRetentionLeases(), equalTo(leasesOnPrimary));
}
}
}

static final class SyncRetentionLeasesResponse extends ReplicationResponse {
final RetentionLeaseSyncAction.Request syncRequest;
SyncRetentionLeasesResponse(RetentionLeaseSyncAction.Request syncRequest) {
this.syncRequest = syncRequest;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.VersionFieldMapper;
import org.elasticsearch.index.seqno.RetentionLeaseSyncer;
import org.elasticsearch.index.seqno.RetentionLeases;
import org.elasticsearch.index.seqno.SeqNoStats;
import org.elasticsearch.index.seqno.SequenceNumbers;
Expand Down Expand Up @@ -1046,8 +1047,8 @@ public void testGlobalCheckpointSync() throws IOException {
final IndexMetaData.Builder indexMetadata =
IndexMetaData.builder(shardRouting.getIndexName()).settings(settings).primaryTerm(0, 1);
final AtomicBoolean synced = new AtomicBoolean();
final IndexShard primaryShard =
newShard(shardRouting, indexMetadata.build(), null, new InternalEngineFactory(), () -> synced.set(true));
final IndexShard primaryShard = newShard(
shardRouting, indexMetadata.build(), null, new InternalEngineFactory(), () -> synced.set(true), RetentionLeaseSyncer.EMPTY);
// add a replica
recoverShardFromStore(primaryShard);
final IndexShard replicaShard = newShard(shardId, false);
Expand Down Expand Up @@ -1462,9 +1463,8 @@ public String[] listAll() throws IOException {
};

try (Store store = createStore(shardId, new IndexSettings(metaData, Settings.EMPTY), directory)) {
IndexShard shard = newShard(shardRouting, shardPath, metaData, i -> store,
null, new InternalEngineFactory(), () -> {
}, EMPTY_EVENT_LISTENER);
IndexShard shard = newShard(shardRouting, shardPath, metaData, i -> store, null, new InternalEngineFactory(),
() -> { }, RetentionLeaseSyncer.EMPTY, EMPTY_EVENT_LISTENER);
AtomicBoolean failureCallbackTriggered = new AtomicBoolean(false);
shard.addShardFailureCallback((ig)->failureCallbackTriggered.set(true));

Expand Down Expand Up @@ -2122,6 +2122,7 @@ public void testRecoverFromStoreRemoveStaleOperations() throws Exception {
null,
shard.getEngineFactory(),
shard.getGlobalCheckpointSyncer(),
shard.getRetentionLeaseSyncer(),
EMPTY_EVENT_LISTENER);
DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
newShard.markAsRecovering("store", new RecoveryState(newShard.routingEntry(), localNode, null));
Expand Down Expand Up @@ -2242,6 +2243,7 @@ public IndexSearcher wrap(IndexSearcher searcher) throws EngineException {
wrapper,
new InternalEngineFactory(),
() -> {},
RetentionLeaseSyncer.EMPTY,
EMPTY_EVENT_LISTENER);

recoverShardFromStore(newShard);
Expand Down Expand Up @@ -2396,6 +2398,7 @@ public IndexSearcher wrap(IndexSearcher searcher) throws EngineException {
wrapper,
new InternalEngineFactory(),
() -> {},
RetentionLeaseSyncer.EMPTY,
EMPTY_EVENT_LISTENER);

recoverShardFromStore(newShard);
Expand Down Expand Up @@ -2962,9 +2965,8 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
.put(IndexSettings.INDEX_CHECK_ON_STARTUP.getKey(), randomFrom("true", "checksum")))
.build();

IndexShard corruptedShard = newShard(shardRouting, shardPath, indexMetaData,
null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), EMPTY_EVENT_LISTENER);
IndexShard corruptedShard = newShard(shardRouting, shardPath, indexMetaData, null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), indexShard.getRetentionLeaseSyncer(), EMPTY_EVENT_LISTENER);

final IndexShardRecoveryException indexShardRecoveryException =
expectThrows(IndexShardRecoveryException.class, () -> newStartedShard(p -> corruptedShard, true));
Expand Down Expand Up @@ -3007,9 +3009,8 @@ public void testShardDoesNotStartIfCorruptedMarkerIsPresent() throws Exception {
}

// try to start shard on corrupted files
final IndexShard corruptedShard = newShard(shardRouting, shardPath, indexMetaData,
null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), EMPTY_EVENT_LISTENER);
final IndexShard corruptedShard = newShard(shardRouting, shardPath, indexMetaData, null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), indexShard.getRetentionLeaseSyncer(), EMPTY_EVENT_LISTENER);

final IndexShardRecoveryException exception1 = expectThrows(IndexShardRecoveryException.class,
() -> newStartedShard(p -> corruptedShard, true));
Expand All @@ -3030,9 +3031,8 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO
assertThat("store has to be marked as corrupted", corruptedMarkerCount.get(), equalTo(1));

// try to start another time shard on corrupted files
final IndexShard corruptedShard2 = newShard(shardRouting, shardPath, indexMetaData,
null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), EMPTY_EVENT_LISTENER);
final IndexShard corruptedShard2 = newShard(shardRouting, shardPath, indexMetaData, null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), indexShard.getRetentionLeaseSyncer(), EMPTY_EVENT_LISTENER);

final IndexShardRecoveryException exception2 = expectThrows(IndexShardRecoveryException.class,
() -> newStartedShard(p -> corruptedShard2, true));
Expand Down Expand Up @@ -3070,9 +3070,8 @@ public void testReadSnapshotAndCheckIndexConcurrently() throws Exception {
.put(indexShard.indexSettings.getSettings())
.put(IndexSettings.INDEX_CHECK_ON_STARTUP.getKey(), randomFrom("false", "true", "checksum")))
.build();
final IndexShard newShard = newShard(shardRouting, indexShard.shardPath(), indexMetaData,
null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), EMPTY_EVENT_LISTENER);
final IndexShard newShard = newShard(shardRouting, indexShard.shardPath(), indexMetaData, null, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), indexShard.getRetentionLeaseSyncer(), EMPTY_EVENT_LISTENER);

Store.MetadataSnapshot storeFileMetaDatas = newShard.snapshotStoreMetadata();
assertTrue("at least 2 files, commit and data: " + storeFileMetaDatas.toString(), storeFileMetaDatas.size() > 1);
Expand Down Expand Up @@ -3482,15 +3481,14 @@ public void testFlushOnInactive() throws Exception {
ShardPath shardPath = new ShardPath(false, nodePath.resolve(shardId), nodePath.resolve(shardId), shardId);
AtomicBoolean markedInactive = new AtomicBoolean();
AtomicReference<IndexShard> primaryRef = new AtomicReference<>();
IndexShard primary = newShard(shardRouting, shardPath, metaData, null, null,
new InternalEngineFactory(), () -> {
}, new IndexEventListener() {
@Override
public void onShardInactive(IndexShard indexShard) {
markedInactive.set(true);
primaryRef.get().flush(new FlushRequest());
}
});
IndexShard primary = newShard(shardRouting, shardPath, metaData, null, null, new InternalEngineFactory(), () -> { },
RetentionLeaseSyncer.EMPTY, new IndexEventListener() {
@Override
public void onShardInactive(IndexShard indexShard) {
markedInactive.set(true);
primaryRef.get().flush(new FlushRequest());
}
});
primaryRef.set(primary);
recoverShardFromStore(primary);
for (int i = 0; i < 3; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import org.elasticsearch.index.MergePolicyConfig;
import org.elasticsearch.index.engine.EngineException;
import org.elasticsearch.index.engine.InternalEngineFactory;
import org.elasticsearch.index.seqno.RetentionLeaseSyncer;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.translog.TestTranslog;
import org.elasticsearch.index.translog.TranslogCorruptedException;
Expand Down Expand Up @@ -107,11 +108,8 @@ public void setup() throws IOException {
.putMapping("_doc", "{ \"properties\": {} }");
indexMetaData = metaData.build();

indexShard = newStartedShard(p ->
newShard(routing, shardPath, indexMetaData, null, null,
new InternalEngineFactory(), () -> {
}, EMPTY_EVENT_LISTENER),
true);
indexShard = newStartedShard(p -> newShard(routing, shardPath, indexMetaData, null, null,
new InternalEngineFactory(), () -> { }, RetentionLeaseSyncer.EMPTY, EMPTY_EVENT_LISTENER), true);

translogPath = shardPath.resolveTranslog();
indexPath = shardPath.resolveIndex();
Expand Down Expand Up @@ -371,8 +369,8 @@ private IndexShard reopenIndexShard(boolean corrupted) throws IOException {
return new Store(shardId, indexSettings, baseDirectoryWrapper, new DummyShardLock(shardId));
};

return newShard(shardRouting, shardPath, metaData, storeProvider, null,
indexShard.engineFactory, indexShard.getGlobalCheckpointSyncer(), EMPTY_EVENT_LISTENER);
return newShard(shardRouting, shardPath, metaData, storeProvider, null, indexShard.engineFactory,
indexShard.getGlobalCheckpointSyncer(), indexShard.getRetentionLeaseSyncer(), EMPTY_EVENT_LISTENER);
}

private int indexDocs(IndexShard indexShard, boolean flushLast) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.engine.InternalEngineFactory;
import org.elasticsearch.index.seqno.RetentionLeaseSyncer;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardState;
import org.elasticsearch.index.shard.IndexShardTestCase;
Expand Down Expand Up @@ -109,6 +110,7 @@ public void testRestoreSnapshotWithExistingFiles() throws IOException {
null,
new InternalEngineFactory(),
() -> {},
RetentionLeaseSyncer.EMPTY,
EMPTY_EVENT_LISTENER);

// restore the shard
Expand Down
Loading