Skip to content

Commit 2504398

Browse files
committed
Open engine should keep only starting commit (#28228)
Keeping unsafe commits when opening an engine can be problematic because these commits are not safe at the recovering time but they can suddenly become safe in the future. The following issues can happen if unsafe commits are kept oninit. 1. Replica can use unsafe commit in peer-recovery. This happens when a replica with a safe commit c1 (max_seqno=1) and an unsafe commit c2 (max_seqno=2) recovers from a primary with c1(max_seqno=1). If a new document (seqno=2) is added without flushing, the global checkpoint is advanced to 2; and the replica recovers again, it will use the unsafe commit c2 (max_seqno=2 <= gcp=2) as the starting commit for sequenced based recovery even the commit c2 contains a stale operation and the document (with seqno=2) will not be replicated to the replica. 2. Min translog gen for recovery can go backwards in peer-recovery. This happens when a replica with a safe commit c1 (local_checkpoint=1, recovery_translog_gen=1) and an unsafe commit c2 (local_checkpoint=2, recovery_translog_gen=2). The replica recovers from a primary, and keeps c2 as the last commit, then sets last_translog_gen to 2. Flushing a new commit on the replica will cause exception as the new last commit c3 will have recovery_translog_gen=1. The recovery translog generation of a commit is calculated based on the current local checkpoint. The local checkpoint of c3 is 1 while the local checkpoint of c2 is 2. 3. Commit without translog can be used for recovery. An old index, which was created before multiple-commits is introduced (v6.2), may not have a safe commit. If that index has a snapshotted commit without translog and an unsafe commit, the policy can consider the snapshotted commit as a safe commit for recovery even the commit does not have translog. These issues can be avoided if the combined deletion policy keeps only the starting commit onInit. Relates #27804 Relates #28181
1 parent c3e5b04 commit 2504398

File tree

8 files changed

+243
-80
lines changed

8 files changed

+243
-80
lines changed

server/src/main/java/org/elasticsearch/index/engine/CombinedDeletionPolicy.java

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,37 +45,72 @@ public final class CombinedDeletionPolicy extends IndexDeletionPolicy {
4545
private final TranslogDeletionPolicy translogDeletionPolicy;
4646
private final EngineConfig.OpenMode openMode;
4747
private final LongSupplier globalCheckpointSupplier;
48+
private final IndexCommit startingCommit;
4849
private final ObjectIntHashMap<IndexCommit> snapshottedCommits; // Number of snapshots held against each commit point.
4950
private IndexCommit safeCommit; // the most recent safe commit point - its max_seqno at most the persisted global checkpoint.
5051
private IndexCommit lastCommit; // the most recent commit point
5152

5253
CombinedDeletionPolicy(EngineConfig.OpenMode openMode, TranslogDeletionPolicy translogDeletionPolicy,
53-
LongSupplier globalCheckpointSupplier) {
54+
LongSupplier globalCheckpointSupplier, IndexCommit startingCommit) {
5455
this.openMode = openMode;
5556
this.translogDeletionPolicy = translogDeletionPolicy;
5657
this.globalCheckpointSupplier = globalCheckpointSupplier;
58+
this.startingCommit = startingCommit;
5759
this.snapshottedCommits = new ObjectIntHashMap<>();
5860
}
5961

6062
@Override
61-
public void onInit(List<? extends IndexCommit> commits) throws IOException {
63+
public synchronized void onInit(List<? extends IndexCommit> commits) throws IOException {
6264
switch (openMode) {
6365
case CREATE_INDEX_AND_TRANSLOG:
66+
assert startingCommit == null : "CREATE_INDEX_AND_TRANSLOG must not have starting commit; commit [" + startingCommit + "]";
6467
break;
6568
case OPEN_INDEX_CREATE_TRANSLOG:
66-
assert commits.isEmpty() == false : "index is opened, but we have no commits";
67-
// When an engine starts with OPEN_INDEX_CREATE_TRANSLOG, a new fresh index commit will be created immediately.
68-
// We therefore can simply skip processing here as `onCommit` will be called right after with a new commit.
69-
break;
7069
case OPEN_INDEX_AND_TRANSLOG:
7170
assert commits.isEmpty() == false : "index is opened, but we have no commits";
72-
onCommit(commits);
71+
assert startingCommit != null && commits.contains(startingCommit) : "Starting commit not in the existing commit list; "
72+
+ "startingCommit [" + startingCommit + "], commit list [" + commits + "]";
73+
keepOnlyStartingCommitOnInit(commits);
74+
// OPEN_INDEX_CREATE_TRANSLOG can open an index commit from other shard with a different translog history,
75+
// We therefore should not use that index commit to update the translog deletion policy.
76+
if (openMode == EngineConfig.OpenMode.OPEN_INDEX_AND_TRANSLOG) {
77+
updateTranslogDeletionPolicy();
78+
}
7379
break;
7480
default:
7581
throw new IllegalArgumentException("unknown openMode [" + openMode + "]");
7682
}
7783
}
7884

85+
/**
86+
* Keeping existing unsafe commits when opening an engine can be problematic because these commits are not safe
87+
* at the recovering time but they can suddenly become safe in the future.
88+
* The following issues can happen if unsafe commits are kept oninit.
89+
* <p>
90+
* 1. Replica can use unsafe commit in peer-recovery. This happens when a replica with a safe commit c1(max_seqno=1)
91+
* and an unsafe commit c2(max_seqno=2) recovers from a primary with c1(max_seqno=1). If a new document(seqno=2)
92+
* is added without flushing, the global checkpoint is advanced to 2; and the replica recovers again, it will use
93+
* the unsafe commit c2(max_seqno=2 at most gcp=2) as the starting commit for sequenced-based recovery even the
94+
* commit c2 contains a stale operation and the document(with seqno=2) will not be replicated to the replica.
95+
* <p>
96+
* 2. Min translog gen for recovery can go backwards in peer-recovery. This happens when are replica with a safe commit
97+
* c1(local_checkpoint=1, recovery_translog_gen=1) and an unsafe commit c2(local_checkpoint=2, recovery_translog_gen=2).
98+
* The replica recovers from a primary, and keeps c2 as the last commit, then sets last_translog_gen to 2. Flushing a new
99+
* commit on the replica will cause exception as the new last commit c3 will have recovery_translog_gen=1. The recovery
100+
* translog generation of a commit is calculated based on the current local checkpoint. The local checkpoint of c3 is 1
101+
* while the local checkpoint of c2 is 2.
102+
* <p>
103+
* 3. Commit without translog can be used in recovery. An old index, which was created before multiple-commits is introduced
104+
* (v6.2), may not have a safe commit. If that index has a snapshotted commit without translog and an unsafe commit,
105+
* the policy can consider the snapshotted commit as a safe commit for recovery even the commit does not have translog.
106+
*/
107+
private void keepOnlyStartingCommitOnInit(List<? extends IndexCommit> commits) {
108+
commits.stream().filter(commit -> startingCommit.equals(commit) == false).forEach(IndexCommit::delete);
109+
assert startingCommit.isDeleted() == false : "Starting commit must not be deleted";
110+
lastCommit = startingCommit;
111+
safeCommit = startingCommit;
112+
}
113+
79114
@Override
80115
public synchronized void onCommit(List<? extends IndexCommit> commits) throws IOException {
81116
final int keptPosition = indexOfKeptCommits(commits, globalCheckpointSupplier.getAsLong());

server/src/main/java/org/elasticsearch/index/engine/Engine.java

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -567,27 +567,6 @@ public CommitStats commitStats() {
567567
*/
568568
public abstract LocalCheckpointTracker getLocalCheckpointTracker();
569569

570-
/**
571-
* Read the last segments info from the commit pointed to by the searcher manager
572-
*/
573-
protected static SegmentInfos readLastCommittedSegmentInfos(final ReferenceManager<IndexSearcher> sm, final Store store) throws IOException {
574-
IndexSearcher searcher = sm.acquire();
575-
try {
576-
IndexCommit latestCommit = ((DirectoryReader) searcher.getIndexReader()).getIndexCommit();
577-
return Lucene.readSegmentInfos(latestCommit);
578-
} catch (IOException e) {
579-
// Fall back to reading from the store if reading from the commit fails
580-
try {
581-
return store.readLastCommittedSegmentsInfo();
582-
} catch (IOException e2) {
583-
e2.addSuppressed(e);
584-
throw e2;
585-
}
586-
} finally {
587-
sm.release(searcher);
588-
}
589-
}
590-
591570
/**
592571
* Global stats on segments.
593572
*/

server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java

Lines changed: 44 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ public InternalEngine(EngineConfig engineConfig) {
186186
assert translog.getGeneration() != null;
187187
this.translog = translog;
188188
this.combinedDeletionPolicy = new CombinedDeletionPolicy(openMode, translogDeletionPolicy,
189-
translog::getLastSyncedGlobalCheckpoint);
189+
translog::getLastSyncedGlobalCheckpoint, startingCommit);
190190
writer = createWriter(openMode == EngineConfig.OpenMode.CREATE_INDEX_AND_TRANSLOG, startingCommit);
191191
updateMaxUnsafeAutoIdTimestampFromWriter(writer);
192192
assert engineConfig.getForceNewHistoryUUID() == false
@@ -416,41 +416,56 @@ public void skipTranslogRecovery() {
416416
}
417417

418418
private IndexCommit getStartingCommitPoint() throws IOException {
419-
if (openMode == EngineConfig.OpenMode.OPEN_INDEX_AND_TRANSLOG) {
420-
final Path translogPath = engineConfig.getTranslogConfig().getTranslogPath();
421-
final long lastSyncedGlobalCheckpoint = Translog.readGlobalCheckpoint(translogPath);
422-
final List<IndexCommit> existingCommits = DirectoryReader.listCommits(store.directory());
423-
// We may not have a safe commit if an index was create before v6.2; and if there is a snapshotted commit whose full translog
424-
// files are not retained but max_seqno is at most the global checkpoint, we may mistakenly select it as a starting commit.
425-
// To avoid this issue, we only select index commits whose translog files are fully retained.
426-
if (engineConfig.getIndexSettings().getIndexVersionCreated().before(Version.V_6_2_0)) {
427-
final long minRetainedTranslogGen = Translog.readMinReferencedGen(translogPath);
428-
// If we don't have min_translog_gen in translog checkpoint, we can not determine whether a commit point has all
429-
// its required translog or not. It's safer if we just fallback to start from the last commit until we have a new checkpoint.
430-
if (minRetainedTranslogGen == SequenceNumbers.NO_OPS_PERFORMED) {
431-
return existingCommits.get(existingCommits.size() - 1);
432-
}
433-
final List<IndexCommit> recoverableCommits = new ArrayList<>();
434-
for (IndexCommit commit : existingCommits) {
435-
if (minRetainedTranslogGen <= Long.parseLong(commit.getUserData().get(Translog.TRANSLOG_GENERATION_KEY))) {
436-
recoverableCommits.add(commit);
419+
final IndexCommit startingIndexCommit;
420+
final List<IndexCommit> existingCommits;
421+
switch (openMode) {
422+
case CREATE_INDEX_AND_TRANSLOG:
423+
startingIndexCommit = null;
424+
break;
425+
case OPEN_INDEX_CREATE_TRANSLOG:
426+
// Use the last commit
427+
existingCommits = DirectoryReader.listCommits(store.directory());
428+
startingIndexCommit = existingCommits.get(existingCommits.size() - 1);
429+
break;
430+
case OPEN_INDEX_AND_TRANSLOG:
431+
// Use the safe commit
432+
final Path translogPath = engineConfig.getTranslogConfig().getTranslogPath();
433+
final long lastSyncedGlobalCheckpoint = Translog.readGlobalCheckpoint(translogPath);
434+
existingCommits = DirectoryReader.listCommits(store.directory());
435+
// We may not have a safe commit if an index was create before v6.2; and if there is a snapshotted commit whose translog
436+
// are not retained but max_seqno is at most the global checkpoint, we may mistakenly select it as a starting commit.
437+
// To avoid this issue, we only select index commits whose translog are fully retained.
438+
if (engineConfig.getIndexSettings().getIndexVersionCreated().before(Version.V_6_2_0)) {
439+
final long minRetainedTranslogGen = Translog.readMinReferencedGen(translogPath);
440+
// If we don't have min_translog_gen in translog checkpoint, we can not determine whether a commit point has all
441+
// its required translog or not. It's safer if we just fallback to start from the last commit until we have a new checkpoint.
442+
if (minRetainedTranslogGen == SequenceNumbers.NO_OPS_PERFORMED) {
443+
return existingCommits.get(existingCommits.size() - 1);
437444
}
445+
final List<IndexCommit> recoverableCommits = new ArrayList<>();
446+
for (IndexCommit commit : existingCommits) {
447+
if (minRetainedTranslogGen <= Long.parseLong(commit.getUserData().get(Translog.TRANSLOG_GENERATION_KEY))) {
448+
recoverableCommits.add(commit);
449+
}
450+
}
451+
assert recoverableCommits.isEmpty() == false : "No commit point with translog found; " +
452+
"commits [" + existingCommits + "], minRetainedTranslogGen [" + minRetainedTranslogGen + "]";
453+
startingIndexCommit = CombinedDeletionPolicy.findSafeCommitPoint(recoverableCommits, lastSyncedGlobalCheckpoint);
454+
} else {
455+
// TODO: Asserts the starting commit is a safe commit once peer-recovery sets global checkpoint.
456+
startingIndexCommit = CombinedDeletionPolicy.findSafeCommitPoint(existingCommits, lastSyncedGlobalCheckpoint);
438457
}
439-
assert recoverableCommits.isEmpty() == false : "No commit point with full translog found; " +
440-
"commits [" + existingCommits + "], minRetainedTranslogGen [" + minRetainedTranslogGen + "]";
441-
return CombinedDeletionPolicy.findSafeCommitPoint(recoverableCommits, lastSyncedGlobalCheckpoint);
442-
} else {
443-
return CombinedDeletionPolicy.findSafeCommitPoint(existingCommits, lastSyncedGlobalCheckpoint);
444-
}
458+
break;
459+
default:
460+
throw new IllegalArgumentException("unknown mode: " + openMode);
445461
}
446-
return null;
462+
return startingIndexCommit;
447463
}
448464

449465
private void recoverFromTranslogInternal() throws IOException {
450466
Translog.TranslogGeneration translogGeneration = translog.getGeneration();
451467
final int opsRecovered;
452-
final IndexCommit startingCommit = indexWriter.getConfig().getIndexCommit();
453-
final long translogGen = Long.parseLong(startingCommit.getUserData().get(Translog.TRANSLOG_GENERATION_KEY));
468+
final long translogGen = Long.parseLong(lastCommittedSegmentInfos.getUserData().get(Translog.TRANSLOG_GENERATION_KEY));
454469
try (Translog.Snapshot snapshot = translog.newSnapshotFromGen(translogGen)) {
455470
opsRecovered = config().getTranslogRecoveryRunner().run(this, snapshot);
456471
} catch (Exception e) {
@@ -578,7 +593,7 @@ private ExternalSearcherManager createSearcherManager(SearchFactory externalSear
578593
final DirectoryReader directoryReader = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(indexWriter), shardId);
579594
internalSearcherManager = new SearcherManager(directoryReader,
580595
new RamAccountingSearcherFactory(engineConfig.getCircuitBreakerService()));
581-
lastCommittedSegmentInfos = readLastCommittedSegmentInfos(internalSearcherManager, store);
596+
lastCommittedSegmentInfos = store.readLastCommittedSegmentsInfo();
582597
ExternalSearcherManager externalSearcherManager = new ExternalSearcherManager(internalSearcherManager,
583598
externalSearcherFactory);
584599
success = true;

server/src/main/java/org/elasticsearch/index/shard/IndexShard.java

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import org.apache.logging.log4j.Logger;
2424
import org.apache.logging.log4j.message.ParameterizedMessage;
2525
import org.apache.lucene.index.CheckIndex;
26+
import org.apache.lucene.index.DirectoryReader;
2627
import org.apache.lucene.index.IndexCommit;
2728
import org.apache.lucene.index.IndexOptions;
2829
import org.apache.lucene.index.LeafReaderContext;
@@ -1303,12 +1304,16 @@ public void createIndexAndTranslog() throws IOException {
13031304

13041305
/** opens the engine on top of the existing lucene engine but creates an empty translog **/
13051306
public void openIndexAndCreateTranslog(boolean forceNewHistoryUUID, long globalCheckpoint) throws IOException {
1306-
assert recoveryState.getRecoverySource().getType() != RecoverySource.Type.EMPTY_STORE &&
1307-
recoveryState.getRecoverySource().getType() != RecoverySource.Type.EXISTING_STORE;
1308-
SequenceNumbers.CommitInfo commitInfo = store.loadSeqNoInfo(null);
1309-
assert commitInfo.localCheckpoint >= globalCheckpoint :
1310-
"trying to create a shard whose local checkpoint [" + commitInfo.localCheckpoint + "] is < global checkpoint ["
1307+
if (Assertions.ENABLED) {
1308+
assert recoveryState.getRecoverySource().getType() != RecoverySource.Type.EMPTY_STORE &&
1309+
recoveryState.getRecoverySource().getType() != RecoverySource.Type.EXISTING_STORE;
1310+
SequenceNumbers.CommitInfo commitInfo = store.loadSeqNoInfo(null);
1311+
assert commitInfo.localCheckpoint >= globalCheckpoint :
1312+
"trying to create a shard whose local checkpoint [" + commitInfo.localCheckpoint + "] is < global checkpoint ["
13111313
+ globalCheckpoint + "]";
1314+
final List<IndexCommit> existingCommits = DirectoryReader.listCommits(store.directory());
1315+
assert existingCommits.size() == 1 : "Open index create translog should have one commit, commits[" + existingCommits + "]";
1316+
}
13121317
globalCheckpointTracker.updateGlobalCheckpointOnReplica(globalCheckpoint, "opening index with a new translog");
13131318
innerOpenEngineAndTranslog(EngineConfig.OpenMode.OPEN_INDEX_CREATE_TRANSLOG, forceNewHistoryUUID);
13141319
assertSequenceNumbersInCommit();

server/src/main/java/org/elasticsearch/index/store/Store.java

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -182,17 +182,9 @@ public Directory directory() {
182182
* @throws IOException if the index is corrupted or the segments file is not present
183183
*/
184184
public SegmentInfos readLastCommittedSegmentsInfo() throws IOException {
185-
return readCommittedSegmentsInfo(null);
186-
}
187-
188-
/**
189-
* Returns the committed segments info for the given commit point.
190-
* If the commit point is not provided, this method will return the segments info of the last commit in the store.
191-
*/
192-
public SegmentInfos readCommittedSegmentsInfo(final IndexCommit commit) throws IOException {
193185
failIfCorrupted();
194186
try {
195-
return readSegmentsInfo(commit, directory());
187+
return readSegmentsInfo(null, directory());
196188
} catch (CorruptIndexException ex) {
197189
markStoreCorrupted(ex);
198190
throw ex;

0 commit comments

Comments
 (0)