Package org.elasticsearch.index.engine
Class Engine
- java.lang.Object
-
- org.elasticsearch.index.engine.Engine
-
- All Implemented Interfaces:
java.io.Closeable,java.lang.AutoCloseable
- Direct Known Subclasses:
InternalEngine
public abstract class Engine extends java.lang.Object implements java.io.Closeable
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classEngine.CommitIdstatic classEngine.Deletestatic classEngine.DeleteResultstatic interfaceEngine.EventListenerstatic classEngine.Getstatic classEngine.GetResultstatic classEngine.Indexstatic classEngine.IndexCommitRefstatic classEngine.IndexResultprotected static classEngine.IndexThrottleA throttling class that can be activated, causing theacquireThrottlemethod to block on a lock when throttling is enabledstatic classEngine.NoOpprotected static classEngine.NoOpLockA Lock implementation that always allows the lock to be acquiredstatic classEngine.NoOpResultstatic classEngine.Operationstatic classEngine.ResultBase class for index and delete operation results Holds result meta data (e.g.static classEngine.Searcherstatic classEngine.SearcherScopestatic classEngine.SyncedFlushResultstatic interfaceEngine.WarmerCalled for each new opened engine searcher to warm new segments
-
Field Summary
Fields Modifier and Type Field Description protected java.lang.StringallocationIdprotected EngineConfigengineConfigprotected Engine.EventListenereventListenerprotected org.apache.lucene.util.SetOnce<java.lang.Exception>failedEngineprotected java.util.concurrent.locks.ReentrantLockfailEngineLockstatic java.lang.StringHISTORY_UUID_KEYprotected java.util.concurrent.atomic.AtomicBooleanisClosedprotected longlastWriteNanosprotected org.apache.logging.log4j.Loggerloggerprotected ReleasableLockreadLockprotected java.util.concurrent.locks.ReentrantReadWriteLockrwlprotected ShardIdshardIdprotected Storestorestatic java.lang.StringSYNC_COMMIT_IDprotected ReleasableLockwriteLock
-
Constructor Summary
Constructors Modifier Constructor Description protectedEngine(EngineConfig engineConfig)
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description abstract Engine.IndexCommitRefacquireLastIndexCommit(boolean flushFirst)Snapshots the most recent index and returns a handle to it.abstract Engine.IndexCommitRefacquireSafeIndexCommit()Snapshots the most recent safe index commit from the engine.Engine.SearcheracquireSearcher(java.lang.String source)Returns a new searcher instance.abstract Engine.SearcheracquireSearcher(java.lang.String source, Engine.SearcherScope scope)Returns a new searcher instance.abstract java.io.CloseableacquireTranslogRetentionLock()abstract voidactivateThrottling()Request that this engine throttle incoming indexing requests to one thread.voidclose()protected abstract voidcloseNoLock(java.lang.String reason, java.util.concurrent.CountDownLatch closedLatch)Method to close the engine while the write lock is held.CommitStatscommitStats()get commits stats for the last commitEngineConfigconfig()abstract voiddeactivateThrottling()Reverses a previousactivateThrottling()call.abstract Engine.DeleteResultdelete(Engine.Delete delete)Perform document delete operation on the engineprotected voidensureOpen()protected voidensureOpen(java.lang.Exception suppressed)abstract booleanensureTranslogSynced(java.util.stream.Stream<Translog.Location> locations)Ensures that all locations in the given stream have been written to the underlying storage.abstract intestimateTranslogOperationsFromMinSeq(long minSeqNo)Returns the estimated number of translog operations in this engine whose seq# at least the provided seq#.voidfailEngine(java.lang.String reason, java.lang.Exception failure)fail engine due to some error.abstract intfillSeqNoGaps(long primaryTerm)Fills up the local checkpoints history with no-ops until the local checkpoint and the max seen sequence ID are identical.abstract Engine.CommitIdflush()Flushes the state of the engine including the transaction log, clearing memory and persisting documents in the lucene index to disk including a potentially heavy and durable fsync operation.abstract Engine.CommitIdflush(boolean force, boolean waitIfOngoing)Flushes the state of the engine including the transaction log, clearing memory.voidflushAndClose()Flush the engine (committing segments to disk and truncating the translog) and close it.voidforceMerge(boolean flush)Force merges to 1 segmentabstract voidforceMerge(boolean flush, int maxNumSegments, boolean onlyExpungeDeletes, boolean upgrade, boolean upgradeOnlyAncientSegments)Triggers a forced merge on this engineabstract Engine.GetResultget(Engine.Get get, java.util.function.BiFunction<java.lang.String,Engine.SearcherScope,Engine.Searcher> searcherFactory)protected Engine.GetResultgetFromSearcher(Engine.Get get, java.util.function.BiFunction<java.lang.String,Engine.SearcherScope,Engine.Searcher> searcherFactory, Engine.SearcherScope scope)abstract java.lang.StringgetHistoryUUID()returns the history uuid for the engineabstract longgetIndexBufferRAMBytesUsed()How much heap is used that would be freed by a refresh.abstract longgetIndexThrottleTimeInMillis()Returns the number of milliseconds this engine was under index throttling.protected abstract org.apache.lucene.index.SegmentInfosgetLastCommittedSegmentInfos()abstract longgetLastSyncedGlobalCheckpoint()Returns the latest global checkpoint value that has been persisted in the underlying storage (i.e.longgetLastWriteNanos()Returns the timestamp of the last write in nanoseconds.abstract longgetLocalCheckpoint()MergeStatsgetMergeStats()protected Segment[]getSegmentInfo(org.apache.lucene.index.SegmentInfos lastCommittedSegmentInfos, boolean verbose)abstract SeqNoStatsgetSeqNoStats(long globalCheckpoint)abstract Translog.LocationgetTranslogLastWriteLocation()Returns the last location that the translog of this engine has written into.abstract TranslogStatsgetTranslogStats()abstract longgetWritingBytes()Returns how many bytes we are currently moving from heap to diskprotected static longguardedRamBytesUsed(org.apache.lucene.util.Accountable a)Returns 0 in the case where accountable is null, otherwise returnsramBytesUsed()abstract Engine.IndexResultindex(Engine.Index index)Perform document index operation on the engineprotected static booleanisMergedSegment(org.apache.lucene.index.LeafReader reader)Returns whether a leaf reader comes from a merge (versus flush or addIndexes).booleanisRecovering()Returnstrueiff this engine is currently recovering from translog.abstract booleanisThrottled()Returns thetrueiff this engine is currently under index throttling.abstract booleanisTranslogSyncNeeded()Checks if the underlying storage sync is required.protected booleanmaybeFailEngine(java.lang.String source, java.lang.Exception e)Check whether the engine should be failedabstract voidmaybePruneDeletes()Tries to prune buffered deletes from the version map.abstract Translog.SnapshotnewTranslogSnapshotFromMinSeqNo(long minSeqNo)Creates a new translog snapshot from this engine for reading translog operations whose seq# at least the provided seq#.abstract Engine.NoOpResultnoOp(Engine.NoOp noOp)voidonSettingsChanged()abstract EnginerecoverFromTranslog()Performs recovery from the transaction log.abstract voidrefresh(java.lang.String source)Synchronously refreshes the engine for new search operations to reflect the latest changes.booleanrefreshNeeded()abstract voidresetLocalCheckpoint(long localCheckpoint)Reset the local checkpoint in the tracker to the given local checkpointabstract voidrestoreLocalCheckpointFromTranslog()Marks operations in the translog as completed.abstract voidrollTranslogGeneration()Rolls the translog generation and cleans unneeded.abstract java.util.List<Segment>segments(boolean verbose)The list of segments in the engine.SegmentsStatssegmentsStats(boolean includeSegmentFileSizes)Global stats on segments.abstract booleanshouldPeriodicallyFlush()Checks if this engine should be flushed periodically.abstract booleanshouldRollTranslogGeneration()Tests whether or not the translog generation should be rolled to a new generation.abstract voidskipTranslogRecovery()Do not replay translog operations, but make the engine be ready.abstract Engine.SyncedFlushResultsyncFlush(java.lang.String syncId, Engine.CommitId expectedCommitId)Attempts to do a special commit where the given syncID is put into the commit data.abstract voidsyncTranslog()abstract voidtrimOperationsFromTranslog(long belowTerm, long aboveSeqNo)Trims translog for terms belowbelowTermand seq# aboveaboveSeqNoabstract voidtrimUnreferencedTranslogFiles()checks and removes translog files that no longer need to be retained.abstract voidwaitForOpsToComplete(long seqNo)Waits for all operations up to the provided sequence number to complete.abstract voidwriteIndexingBuffer()Called when our engine is using too much heap and should move buffered indexed/deleted documents to disk.protected voidwriterSegmentStats(SegmentsStats stats)
-
-
-
Field Detail
-
SYNC_COMMIT_ID
public static final java.lang.String SYNC_COMMIT_ID
- See Also:
- Constant Field Values
-
HISTORY_UUID_KEY
public static final java.lang.String HISTORY_UUID_KEY
- See Also:
- Constant Field Values
-
shardId
protected final ShardId shardId
-
allocationId
protected final java.lang.String allocationId
-
logger
protected final org.apache.logging.log4j.Logger logger
-
engineConfig
protected final EngineConfig engineConfig
-
store
protected final Store store
-
isClosed
protected final java.util.concurrent.atomic.AtomicBoolean isClosed
-
eventListener
protected final Engine.EventListener eventListener
-
failEngineLock
protected final java.util.concurrent.locks.ReentrantLock failEngineLock
-
rwl
protected final java.util.concurrent.locks.ReentrantReadWriteLock rwl
-
readLock
protected final ReleasableLock readLock
-
writeLock
protected final ReleasableLock writeLock
-
failedEngine
protected final org.apache.lucene.util.SetOnce<java.lang.Exception> failedEngine
-
lastWriteNanos
protected volatile long lastWriteNanos
-
-
Constructor Detail
-
Engine
protected Engine(EngineConfig engineConfig)
-
-
Method Detail
-
guardedRamBytesUsed
protected static long guardedRamBytesUsed(org.apache.lucene.util.Accountable a)
Returns 0 in the case where accountable is null, otherwise returnsramBytesUsed()
-
isMergedSegment
protected static boolean isMergedSegment(org.apache.lucene.index.LeafReader reader)
Returns whether a leaf reader comes from a merge (versus flush or addIndexes).
-
config
public final EngineConfig config()
-
getLastCommittedSegmentInfos
protected abstract org.apache.lucene.index.SegmentInfos getLastCommittedSegmentInfos()
-
getMergeStats
public MergeStats getMergeStats()
-
getHistoryUUID
public abstract java.lang.String getHistoryUUID()
returns the history uuid for the engine
-
getWritingBytes
public abstract long getWritingBytes()
Returns how many bytes we are currently moving from heap to disk
-
getIndexThrottleTimeInMillis
public abstract long getIndexThrottleTimeInMillis()
Returns the number of milliseconds this engine was under index throttling.
-
isThrottled
public abstract boolean isThrottled()
Returns thetrueiff this engine is currently under index throttling.- See Also:
getIndexThrottleTimeInMillis()
-
trimOperationsFromTranslog
public abstract void trimOperationsFromTranslog(long belowTerm, long aboveSeqNo) throws EngineExceptionTrims translog for terms belowbelowTermand seq# aboveaboveSeqNo- Throws:
EngineException- See Also:
Translog.trimOperations(long, long)
-
index
public abstract Engine.IndexResult index(Engine.Index index) throws java.io.IOException
Perform document index operation on the engine- Parameters:
index- operation to perform- Returns:
Engine.IndexResultcontaining updated translog location, version and document specific failures Note: engine level failures (i.e. persistent engine failures) are thrown- Throws:
java.io.IOException
-
delete
public abstract Engine.DeleteResult delete(Engine.Delete delete) throws java.io.IOException
Perform document delete operation on the engine- Parameters:
delete- operation to perform- Returns:
Engine.DeleteResultcontaining updated translog location, version and document specific failures Note: engine level failures (i.e. persistent engine failures) are thrown- Throws:
java.io.IOException
-
noOp
public abstract Engine.NoOpResult noOp(Engine.NoOp noOp)
-
syncFlush
public abstract Engine.SyncedFlushResult syncFlush(java.lang.String syncId, Engine.CommitId expectedCommitId) throws EngineException
Attempts to do a special commit where the given syncID is put into the commit data. The attempt succeeds if there are not pending writes in lucene and the current point is equal to the expected one.- Parameters:
syncId- id of this syncexpectedCommitId- the expected value of- Returns:
- true if the sync commit was made, false o.w.
- Throws:
EngineException
-
getFromSearcher
protected final Engine.GetResult getFromSearcher(Engine.Get get, java.util.function.BiFunction<java.lang.String,Engine.SearcherScope,Engine.Searcher> searcherFactory, Engine.SearcherScope scope) throws EngineException
- Throws:
EngineException
-
get
public abstract Engine.GetResult get(Engine.Get get, java.util.function.BiFunction<java.lang.String,Engine.SearcherScope,Engine.Searcher> searcherFactory) throws EngineException
- Throws:
EngineException
-
acquireSearcher
public final Engine.Searcher acquireSearcher(java.lang.String source) throws EngineException
Returns a new searcher instance. The consumer of this API is responsible for releasing the returned searcher in a safe manner, preferably in a try/finally block.- Parameters:
source- the source API or routing that triggers this searcher acquire- Throws:
EngineException- See Also:
Engine.Searcher.close()
-
acquireSearcher
public abstract Engine.Searcher acquireSearcher(java.lang.String source, Engine.SearcherScope scope) throws EngineException
Returns a new searcher instance. The consumer of this API is responsible for releasing the returned searcher in a safe manner, preferably in a try/finally block.- Parameters:
source- the source API or routing that triggers this searcher acquirescope- the scope of this searcher ie. if the searcher will be used for get or search purposes- Throws:
EngineException- See Also:
Engine.Searcher.close()
-
isTranslogSyncNeeded
public abstract boolean isTranslogSyncNeeded()
Checks if the underlying storage sync is required.
-
ensureTranslogSynced
public abstract boolean ensureTranslogSynced(java.util.stream.Stream<Translog.Location> locations) throws java.io.IOException
Ensures that all locations in the given stream have been written to the underlying storage.- Throws:
java.io.IOException
-
syncTranslog
public abstract void syncTranslog() throws java.io.IOException- Throws:
java.io.IOException
-
acquireTranslogRetentionLock
public abstract java.io.Closeable acquireTranslogRetentionLock()
-
newTranslogSnapshotFromMinSeqNo
public abstract Translog.Snapshot newTranslogSnapshotFromMinSeqNo(long minSeqNo) throws java.io.IOException
Creates a new translog snapshot from this engine for reading translog operations whose seq# at least the provided seq#. The caller has to close the returned snapshot after finishing the reading.- Throws:
java.io.IOException
-
estimateTranslogOperationsFromMinSeq
public abstract int estimateTranslogOperationsFromMinSeq(long minSeqNo)
Returns the estimated number of translog operations in this engine whose seq# at least the provided seq#.
-
getTranslogStats
public abstract TranslogStats getTranslogStats()
-
getTranslogLastWriteLocation
public abstract Translog.Location getTranslogLastWriteLocation()
Returns the last location that the translog of this engine has written into.
-
ensureOpen
protected final void ensureOpen(java.lang.Exception suppressed)
-
ensureOpen
protected final void ensureOpen()
-
commitStats
public CommitStats commitStats()
get commits stats for the last commit
-
getLocalCheckpoint
public abstract long getLocalCheckpoint()
- Returns:
- the local checkpoint for this Engine
-
waitForOpsToComplete
public abstract void waitForOpsToComplete(long seqNo) throws java.lang.InterruptedExceptionWaits for all operations up to the provided sequence number to complete.- Parameters:
seqNo- the sequence number that the checkpoint must advance to before this method returns- Throws:
java.lang.InterruptedException- if the thread was interrupted while blocking on the condition
-
resetLocalCheckpoint
public abstract void resetLocalCheckpoint(long localCheckpoint)
Reset the local checkpoint in the tracker to the given local checkpoint- Parameters:
localCheckpoint- the new checkpoint to be set
-
getSeqNoStats
public abstract SeqNoStats getSeqNoStats(long globalCheckpoint)
- Returns:
- a
SeqNoStatsobject, using local state and the supplied global checkpoint
-
getLastSyncedGlobalCheckpoint
public abstract long getLastSyncedGlobalCheckpoint()
Returns the latest global checkpoint value that has been persisted in the underlying storage (i.e. translog's checkpoint)
-
segmentsStats
public final SegmentsStats segmentsStats(boolean includeSegmentFileSizes)
Global stats on segments.
-
writerSegmentStats
protected void writerSegmentStats(SegmentsStats stats)
-
getIndexBufferRAMBytesUsed
public abstract long getIndexBufferRAMBytesUsed()
How much heap is used that would be freed by a refresh. Note that this may throwAlreadyClosedException.
-
getSegmentInfo
protected Segment[] getSegmentInfo(org.apache.lucene.index.SegmentInfos lastCommittedSegmentInfos, boolean verbose)
-
segments
public abstract java.util.List<Segment> segments(boolean verbose)
The list of segments in the engine.
-
refreshNeeded
public final boolean refreshNeeded()
-
refresh
@Nullable public abstract void refresh(java.lang.String source) throws EngineException
Synchronously refreshes the engine for new search operations to reflect the latest changes.- Throws:
EngineException
-
writeIndexingBuffer
public abstract void writeIndexingBuffer() throws EngineExceptionCalled when our engine is using too much heap and should move buffered indexed/deleted documents to disk.- Throws:
EngineException
-
shouldPeriodicallyFlush
public abstract boolean shouldPeriodicallyFlush()
Checks if this engine should be flushed periodically. This check is mainly based on the uncommitted translog size and the translog flush threshold setting.
-
flush
public abstract Engine.CommitId flush(boolean force, boolean waitIfOngoing) throws EngineException
Flushes the state of the engine including the transaction log, clearing memory.- Parameters:
force- iftruea lucene commit is executed even if no changes need to be committed.waitIfOngoing- iftruethis call will block until all currently running flushes have finished. Otherwise this call will return without blocking.- Returns:
- the commit Id for the resulting commit
- Throws:
EngineException
-
flush
public abstract Engine.CommitId flush() throws EngineException
Flushes the state of the engine including the transaction log, clearing memory and persisting documents in the lucene index to disk including a potentially heavy and durable fsync operation. This operation is not going to block if another flush operation is currently running and won't write a lucene commit if nothing needs to be committed.- Returns:
- the commit Id for the resulting commit
- Throws:
EngineException
-
trimUnreferencedTranslogFiles
public abstract void trimUnreferencedTranslogFiles() throws EngineExceptionchecks and removes translog files that no longer need to be retained. SeeTranslogDeletionPolicyfor details- Throws:
EngineException
-
shouldRollTranslogGeneration
public abstract boolean shouldRollTranslogGeneration()
Tests whether or not the translog generation should be rolled to a new generation. This test is based on the size of the current generation compared to the configured generation threshold size.- Returns:
trueif the current generation should be rolled to a new generation
-
rollTranslogGeneration
public abstract void rollTranslogGeneration() throws EngineExceptionRolls the translog generation and cleans unneeded.- Throws:
EngineException
-
forceMerge
public void forceMerge(boolean flush) throws java.io.IOExceptionForce merges to 1 segment- Throws:
java.io.IOException
-
forceMerge
public abstract void forceMerge(boolean flush, int maxNumSegments, boolean onlyExpungeDeletes, boolean upgrade, boolean upgradeOnlyAncientSegments) throws EngineException, java.io.IOExceptionTriggers a forced merge on this engine- Throws:
EngineExceptionjava.io.IOException
-
acquireLastIndexCommit
public abstract Engine.IndexCommitRef acquireLastIndexCommit(boolean flushFirst) throws EngineException
Snapshots the most recent index and returns a handle to it. If needed will try and "commit" the lucene index to make sure we have a "fresh" copy of the files to snapshot.- Parameters:
flushFirst- indicates whether the engine should flush before returning the snapshot- Throws:
EngineException
-
acquireSafeIndexCommit
public abstract Engine.IndexCommitRef acquireSafeIndexCommit() throws EngineException
Snapshots the most recent safe index commit from the engine.- Throws:
EngineException
-
failEngine
public void failEngine(java.lang.String reason, @Nullable java.lang.Exception failure)fail engine due to some error. the engine will also be closed. The underlying store is marked corrupted iff failure is caused by index corruption
-
maybeFailEngine
protected boolean maybeFailEngine(java.lang.String source, java.lang.Exception e)Check whether the engine should be failed
-
closeNoLock
protected abstract void closeNoLock(java.lang.String reason, java.util.concurrent.CountDownLatch closedLatch)Method to close the engine while the write lock is held. Must decrement the supplied when closing work is done and resources are freed.
-
flushAndClose
public void flushAndClose() throws java.io.IOExceptionFlush the engine (committing segments to disk and truncating the translog) and close it.- Throws:
java.io.IOException
-
close
public void close() throws java.io.IOException- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable- Throws:
java.io.IOException
-
onSettingsChanged
public void onSettingsChanged()
-
getLastWriteNanos
public long getLastWriteNanos()
Returns the timestamp of the last write in nanoseconds. Note: this time might not be absolutely accurate since theEngine.Operation.startTime()is used which might be slightly inaccurate.- See Also:
System.nanoTime(),Engine.Operation.startTime()
-
activateThrottling
public abstract void activateThrottling()
Request that this engine throttle incoming indexing requests to one thread. Must be matched by a later call todeactivateThrottling().
-
deactivateThrottling
public abstract void deactivateThrottling()
Reverses a previousactivateThrottling()call.
-
restoreLocalCheckpointFromTranslog
public abstract void restoreLocalCheckpointFromTranslog() throws java.io.IOExceptionMarks operations in the translog as completed. This is used to restore the state of the local checkpoint tracker on primary promotion.- Throws:
java.io.IOException- if an I/O exception occurred reading the translog
-
fillSeqNoGaps
public abstract int fillSeqNoGaps(long primaryTerm) throws java.io.IOExceptionFills up the local checkpoints history with no-ops until the local checkpoint and the max seen sequence ID are identical.- Parameters:
primaryTerm- the shards primary term this engine was created for- Returns:
- the number of no-ops added
- Throws:
java.io.IOException
-
recoverFromTranslog
public abstract Engine recoverFromTranslog() throws java.io.IOException
Performs recovery from the transaction log. This operation will close the engine if the recovery fails.- Throws:
java.io.IOException
-
skipTranslogRecovery
public abstract void skipTranslogRecovery()
Do not replay translog operations, but make the engine be ready.
-
isRecovering
public boolean isRecovering()
Returnstrueiff this engine is currently recovering from translog.
-
maybePruneDeletes
public abstract void maybePruneDeletes()
Tries to prune buffered deletes from the version map.
-
-