Package org.elasticsearch.index.engine
Class ReadOnlyEngine
- java.lang.Object
-
- org.elasticsearch.index.engine.Engine
-
- org.elasticsearch.index.engine.ReadOnlyEngine
-
- All Implemented Interfaces:
java.io.Closeable,java.lang.AutoCloseable
public class ReadOnlyEngine extends Engine
A basic read-only engine that allows switching a shard to be true read-only temporarily or permanently. Note: this engine can be opened side-by-side with a read-write engine but will not reflect any changes made to the read-write engine.
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class org.elasticsearch.index.engine.Engine
Engine.CommitId, Engine.Delete, Engine.DeleteResult, Engine.EventListener, Engine.Get, Engine.GetResult, Engine.Index, Engine.IndexCommitRef, Engine.IndexResult, Engine.IndexThrottle, Engine.NoOp, Engine.NoOpLock, Engine.NoOpResult, Engine.Operation, Engine.Result, Engine.Searcher, Engine.SearcherScope, Engine.SyncedFlushResult, Engine.TranslogRecoveryRunner, Engine.Warmer
-
-
Field Summary
-
Fields inherited from class org.elasticsearch.index.engine.Engine
allocationId, engineConfig, eventListener, failedEngine, failEngineLock, HISTORY_UUID_KEY, isClosed, lastWriteNanos, logger, MAX_UNSAFE_AUTO_ID_TIMESTAMP_COMMIT_ID, MIN_RETAINED_SEQNO, readLock, rwl, shardId, store, SYNC_COMMIT_ID, writeLock
-
-
Constructor Summary
Constructors Constructor Description ReadOnlyEngine(EngineConfig config, SeqNoStats seqNoStats, TranslogStats translogStats, boolean obtainLock, java.util.function.Function<org.apache.lucene.index.DirectoryReader,org.apache.lucene.index.DirectoryReader> readerWrapperFunction)Creates a new ReadOnlyEngine.
-
Method Summary
Modifier and Type Method Description Engine.IndexCommitRefacquireLastIndexCommit(boolean flushFirst)Snapshots the most recent index and returns a handle to it.java.io.CloseableacquireRetentionLock()Acquires a lock on the translog files and Lucene soft-deleted documents to prevent them from being trimmedEngine.IndexCommitRefacquireSafeIndexCommit()Snapshots the most recent safe index commit from the engine.voidactivateThrottling()Request that this engine throttle incoming indexing requests to one thread.protected voidassertMaxSeqNoEqualsToGlobalCheckpoint(long maxSeqNo, long globalCheckpoint)static SeqNoStatsbuildSeqNoStats(org.apache.lucene.index.SegmentInfos infos)protected voidcloseNoLock(java.lang.String reason, java.util.concurrent.CountDownLatch closedLatch)Method to close the engine while the write lock is held.voiddeactivateThrottling()Reverses a previousEngine.activateThrottling()call.Engine.DeleteResultdelete(Engine.Delete delete)Perform document delete operation on the engineDocsStatsdocStats()Returns theDocsStatsfor this enginebooleanensureTranslogSynced(java.util.stream.Stream<Translog.Location> locations)Ensures that all locations in the given stream have been written to the underlying storage.intestimateNumberOfHistoryOperations(java.lang.String source, MapperService mapperService, long startingSeqNo)Returns the estimated number of history operations whose seq# at leaststartingSeqNo(inclusive) in this engine.intfillSeqNoGaps(long primaryTerm)Fills up the local checkpoints history with no-ops until the local checkpoint and the max seen sequence ID are identical.Engine.CommitIdflush(boolean force, boolean waitIfOngoing)Flushes the state of the engine including the transaction log, clearing memory.voidforceMerge(boolean flush, int maxNumSegments, boolean onlyExpungeDeletes, boolean upgrade, boolean upgradeOnlyAncientSegments)Triggers a forced merge on this engineEngine.GetResultget(Engine.Get get, java.util.function.BiFunction<java.lang.String,Engine.SearcherScope,Engine.Searcher> searcherFactory)java.lang.StringgetHistoryUUID()returns the history uuid for the enginelonggetIndexBufferRAMBytesUsed()How much heap is used that would be freed by a refresh.longgetIndexThrottleTimeInMillis()Returns the number of milliseconds this engine was under index throttling.protected org.apache.lucene.index.SegmentInfosgetLastCommittedSegmentInfos()longgetLastSyncedGlobalCheckpoint()Returns the latest global checkpoint value that has been persisted in the underlying storage (i.e.longgetLocalCheckpoint()longgetMinRetainedSeqNo()Gets the minimum retained sequence number for this engine.protected org.apache.lucene.search.ReferenceManager<org.apache.lucene.search.IndexSearcher>getReferenceManager(Engine.SearcherScope scope)SeqNoStatsgetSeqNoStats(long globalCheckpoint)Translog.LocationgetTranslogLastWriteLocation()Returns the last location that the translog of this engine has written into.TranslogStatsgetTranslogStats()longgetWritingBytes()Returns how many bytes we are currently moving from heap to diskbooleanhasCompleteOperationHistory(java.lang.String source, MapperService mapperService, long startingSeqNo)Checks if this engine has every operations sincestartingSeqNo(inclusive) in its translogEngine.IndexResultindex(Engine.Index index)Perform document index operation on the enginebooleanisThrottled()Returns thetrueiff this engine is currently under index throttling.booleanisTranslogSyncNeeded()Checks if the underlying storage sync is required.voidmaybePruneDeletes()Tries to prune buffered deletes from the version map.Translog.SnapshotnewChangesSnapshot(java.lang.String source, MapperService mapperService, long fromSeqNo, long toSeqNo, boolean requiredFullRange)Creates a new history snapshot from Lucene for reading operations whose seqno in the requesting seqno range (both inclusive).Engine.NoOpResultnoOp(Engine.NoOp noOp)protected org.apache.lucene.index.DirectoryReaderopen(org.apache.lucene.index.IndexCommit commit)protected voidprocessReaders(org.apache.lucene.index.IndexReader reader, org.apache.lucene.index.IndexReader previousReader)Translog.SnapshotreadHistoryOperations(java.lang.String source, MapperService mapperService, long startingSeqNo)Creates a new history snapshot for reading operations sincestartingSeqNo(inclusive).EnginerecoverFromTranslog(Engine.TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo)Performs recovery from the transaction log up torecoverUpToSeqNo(inclusive).voidrefresh(java.lang.String source)Synchronously refreshes the engine for new search operations to reflect the latest changes.booleanrefreshNeeded()voidreinitializeMaxSeqNoOfUpdatesOrDeletes()A primary shard calls this method to re-initialize the max_seq_no_of_updates marker using the max_seq_no from Lucene index and translog before replaying the local translog in its local recovery.intrestoreLocalHistoryFromTranslog(Engine.TranslogRecoveryRunner translogRecoveryRunner)This method replays translog to restore the Lucene index which might be reverted previously.voidrollTranslogGeneration()Rolls the translog generation and cleans unneeded.java.util.List<Segment>segments(boolean verbose)The list of segments in the engine.booleanshouldPeriodicallyFlush()Checks if this engine should be flushed periodically.booleanshouldRollTranslogGeneration()Tests whether or not the translog generation should be rolled to a new generation.voidskipTranslogRecovery()Do not replay translog operations, but make the engine be ready.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.voidsyncTranslog()voidtrimOperationsFromTranslog(long belowTerm, long aboveSeqNo)Trims translog for terms belowbelowTermand seq# aboveaboveSeqNovoidtrimUnreferencedTranslogFiles()checks and removes translog files that no longer need to be retained.voidupdateMaxUnsafeAutoIdTimestamp(long newTimestamp)Forces this engine to advance its max_unsafe_auto_id_timestamp marker to at least the given timestamp.voidverifyEngineBeforeIndexClosing()Performs the pre-closing checks on theEngine.protected org.apache.lucene.index.DirectoryReaderwrapReader(org.apache.lucene.index.DirectoryReader reader, java.util.function.Function<org.apache.lucene.index.DirectoryReader,org.apache.lucene.index.DirectoryReader> readerWrapperFunction)voidwriteIndexingBuffer()Called when our engine is using too much heap and should move buffered indexed/deleted documents to disk.-
Methods inherited from class org.elasticsearch.index.engine.Engine
acquireSearcher, acquireSearcher, advanceMaxSeqNoOfUpdatesOrDeletes, close, commitStats, completionStats, config, docsStats, ensureOpen, ensureOpen, failEngine, flush, flushAndClose, forceMerge, getFromSearcher, getLastWriteNanos, getMaxSeenAutoIdTimestamp, getMaxSeqNoOfUpdatesOrDeletes, getMergeStats, getSegmentInfo, guardedRamBytesUsed, isMergedSegment, isRecovering, maybeFailEngine, onSettingsChanged, segmentsStats, writerSegmentStats
-
-
-
-
Constructor Detail
-
ReadOnlyEngine
public ReadOnlyEngine(EngineConfig config, SeqNoStats seqNoStats, TranslogStats translogStats, boolean obtainLock, java.util.function.Function<org.apache.lucene.index.DirectoryReader,org.apache.lucene.index.DirectoryReader> readerWrapperFunction)
Creates a new ReadOnlyEngine. This ctor can also be used to open a read-only engine on top of an already opened read-write engine. It allows to optionally obtain the writer locks for the shard which would time-out if another engine is still open.- Parameters:
config- the engine configurationseqNoStats- sequence number statistics for this engine or null if not providedtranslogStats- translog stats for this engine or null if not providedobtainLock- iftruethis engine will try to obtain theIndexWriter.WRITE_LOCK_NAMElock. Otherwise the lock won't be obtainedreaderWrapperFunction- allows to wrap the index-reader for this engine.
-
-
Method Detail
-
assertMaxSeqNoEqualsToGlobalCheckpoint
protected void assertMaxSeqNoEqualsToGlobalCheckpoint(long maxSeqNo, long globalCheckpoint)
-
verifyEngineBeforeIndexClosing
public void verifyEngineBeforeIndexClosing() throws java.lang.IllegalStateExceptionDescription copied from class:EnginePerforms the pre-closing checks on theEngine.- Overrides:
verifyEngineBeforeIndexClosingin classEngine- Throws:
java.lang.IllegalStateException- if the sanity checks failed
-
wrapReader
protected final org.apache.lucene.index.DirectoryReader wrapReader(org.apache.lucene.index.DirectoryReader reader, java.util.function.Function<org.apache.lucene.index.DirectoryReader,org.apache.lucene.index.DirectoryReader> readerWrapperFunction) throws java.io.IOException- Throws:
java.io.IOException
-
open
protected org.apache.lucene.index.DirectoryReader open(org.apache.lucene.index.IndexCommit commit) throws java.io.IOException- Throws:
java.io.IOException
-
closeNoLock
protected void closeNoLock(java.lang.String reason, java.util.concurrent.CountDownLatch closedLatch)Description copied from class:EngineMethod to close the engine while the write lock is held. Must decrement the supplied when closing work is done and resources are freed.- Specified by:
closeNoLockin classEngine
-
buildSeqNoStats
public static SeqNoStats buildSeqNoStats(org.apache.lucene.index.SegmentInfos infos)
-
get
public Engine.GetResult get(Engine.Get get, java.util.function.BiFunction<java.lang.String,Engine.SearcherScope,Engine.Searcher> searcherFactory) throws EngineException
- Specified by:
getin classEngine- Throws:
EngineException
-
getReferenceManager
protected org.apache.lucene.search.ReferenceManager<org.apache.lucene.search.IndexSearcher> getReferenceManager(Engine.SearcherScope scope)
- Specified by:
getReferenceManagerin classEngine
-
getLastCommittedSegmentInfos
protected org.apache.lucene.index.SegmentInfos getLastCommittedSegmentInfos()
- Specified by:
getLastCommittedSegmentInfosin classEngine
-
getHistoryUUID
public java.lang.String getHistoryUUID()
Description copied from class:Enginereturns the history uuid for the engine- Specified by:
getHistoryUUIDin classEngine
-
getWritingBytes
public long getWritingBytes()
Description copied from class:EngineReturns how many bytes we are currently moving from heap to disk- Specified by:
getWritingBytesin classEngine
-
getIndexThrottleTimeInMillis
public long getIndexThrottleTimeInMillis()
Description copied from class:EngineReturns the number of milliseconds this engine was under index throttling.- Specified by:
getIndexThrottleTimeInMillisin classEngine
-
isThrottled
public boolean isThrottled()
Description copied from class:EngineReturns thetrueiff this engine is currently under index throttling.- Specified by:
isThrottledin classEngine- See Also:
Engine.getIndexThrottleTimeInMillis()
-
index
public Engine.IndexResult index(Engine.Index index)
Description copied from class:EnginePerform document index operation on the engine- Specified by:
indexin classEngine- 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
-
delete
public Engine.DeleteResult delete(Engine.Delete delete)
Description copied from class:EnginePerform document delete operation on the engine- Specified by:
deletein classEngine- 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
-
noOp
public Engine.NoOpResult noOp(Engine.NoOp noOp)
-
isTranslogSyncNeeded
public boolean isTranslogSyncNeeded()
Description copied from class:EngineChecks if the underlying storage sync is required.- Specified by:
isTranslogSyncNeededin classEngine
-
ensureTranslogSynced
public boolean ensureTranslogSynced(java.util.stream.Stream<Translog.Location> locations)
Description copied from class:EngineEnsures that all locations in the given stream have been written to the underlying storage.- Specified by:
ensureTranslogSyncedin classEngine
-
syncTranslog
public void syncTranslog()
- Specified by:
syncTranslogin classEngine
-
acquireRetentionLock
public java.io.Closeable acquireRetentionLock()
Description copied from class:EngineAcquires a lock on the translog files and Lucene soft-deleted documents to prevent them from being trimmed- Specified by:
acquireRetentionLockin classEngine
-
newChangesSnapshot
public Translog.Snapshot newChangesSnapshot(java.lang.String source, MapperService mapperService, long fromSeqNo, long toSeqNo, boolean requiredFullRange) throws java.io.IOException
Description copied from class:EngineCreates a new history snapshot from Lucene for reading operations whose seqno in the requesting seqno range (both inclusive). This feature requires soft-deletes enabled. If soft-deletes are disabled, this method will throw anIllegalStateException.- Specified by:
newChangesSnapshotin classEngine- Throws:
java.io.IOException
-
readHistoryOperations
public Translog.Snapshot readHistoryOperations(java.lang.String source, MapperService mapperService, long startingSeqNo) throws java.io.IOException
Description copied from class:EngineCreates a new history snapshot for reading operations sincestartingSeqNo(inclusive). The returned snapshot can be retrieved from either Lucene index or translog files.- Specified by:
readHistoryOperationsin classEngine- Throws:
java.io.IOException
-
estimateNumberOfHistoryOperations
public int estimateNumberOfHistoryOperations(java.lang.String source, MapperService mapperService, long startingSeqNo) throws java.io.IOExceptionDescription copied from class:EngineReturns the estimated number of history operations whose seq# at leaststartingSeqNo(inclusive) in this engine.- Specified by:
estimateNumberOfHistoryOperationsin classEngine- Throws:
java.io.IOException
-
hasCompleteOperationHistory
public boolean hasCompleteOperationHistory(java.lang.String source, MapperService mapperService, long startingSeqNo) throws java.io.IOExceptionDescription copied from class:EngineChecks if this engine has every operations sincestartingSeqNo(inclusive) in its translog- Specified by:
hasCompleteOperationHistoryin classEngine- Throws:
java.io.IOException
-
getMinRetainedSeqNo
public long getMinRetainedSeqNo()
Description copied from class:EngineGets the minimum retained sequence number for this engine.- Specified by:
getMinRetainedSeqNoin classEngine- Returns:
- the minimum retained sequence number
-
getTranslogStats
public TranslogStats getTranslogStats()
- Specified by:
getTranslogStatsin classEngine
-
getTranslogLastWriteLocation
public Translog.Location getTranslogLastWriteLocation()
Description copied from class:EngineReturns the last location that the translog of this engine has written into.- Specified by:
getTranslogLastWriteLocationin classEngine
-
getLocalCheckpoint
public long getLocalCheckpoint()
- Specified by:
getLocalCheckpointin classEngine- Returns:
- the local checkpoint for this Engine
-
getSeqNoStats
public SeqNoStats getSeqNoStats(long globalCheckpoint)
- Specified by:
getSeqNoStatsin classEngine- Returns:
- a
SeqNoStatsobject, using local state and the supplied global checkpoint
-
getLastSyncedGlobalCheckpoint
public long getLastSyncedGlobalCheckpoint()
Description copied from class:EngineReturns the latest global checkpoint value that has been persisted in the underlying storage (i.e. translog's checkpoint)- Specified by:
getLastSyncedGlobalCheckpointin classEngine
-
getIndexBufferRAMBytesUsed
public long getIndexBufferRAMBytesUsed()
Description copied from class:EngineHow much heap is used that would be freed by a refresh. Note that this may throwAlreadyClosedException.- Specified by:
getIndexBufferRAMBytesUsedin classEngine
-
segments
public java.util.List<Segment> segments(boolean verbose)
Description copied from class:EngineThe list of segments in the engine.
-
refresh
public void refresh(java.lang.String source)
Description copied from class:EngineSynchronously refreshes the engine for new search operations to reflect the latest changes.
-
writeIndexingBuffer
public void writeIndexingBuffer() throws EngineExceptionDescription copied from class:EngineCalled when our engine is using too much heap and should move buffered indexed/deleted documents to disk.- Specified by:
writeIndexingBufferin classEngine- Throws:
EngineException
-
shouldPeriodicallyFlush
public boolean shouldPeriodicallyFlush()
Description copied from class:EngineChecks if this engine should be flushed periodically. This check is mainly based on the uncommitted translog size and the translog flush threshold setting.- Specified by:
shouldPeriodicallyFlushin classEngine
-
syncFlush
public Engine.SyncedFlushResult syncFlush(java.lang.String syncId, Engine.CommitId expectedCommitId)
Description copied from class:EngineAttempts 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.
-
flush
public Engine.CommitId flush(boolean force, boolean waitIfOngoing) throws EngineException
Description copied from class:EngineFlushes the state of the engine including the transaction log, clearing memory.- Specified by:
flushin classEngine- 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
-
forceMerge
public void forceMerge(boolean flush, int maxNumSegments, boolean onlyExpungeDeletes, boolean upgrade, boolean upgradeOnlyAncientSegments)Description copied from class:EngineTriggers a forced merge on this engine- Specified by:
forceMergein classEngine
-
acquireLastIndexCommit
public Engine.IndexCommitRef acquireLastIndexCommit(boolean flushFirst)
Description copied from class:EngineSnapshots 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.- Specified by:
acquireLastIndexCommitin classEngine- Parameters:
flushFirst- indicates whether the engine should flush before returning the snapshot
-
acquireSafeIndexCommit
public Engine.IndexCommitRef acquireSafeIndexCommit()
Description copied from class:EngineSnapshots the most recent safe index commit from the engine.- Specified by:
acquireSafeIndexCommitin classEngine
-
activateThrottling
public void activateThrottling()
Description copied from class:EngineRequest that this engine throttle incoming indexing requests to one thread. Must be matched by a later call toEngine.deactivateThrottling().- Specified by:
activateThrottlingin classEngine
-
deactivateThrottling
public void deactivateThrottling()
Description copied from class:EngineReverses a previousEngine.activateThrottling()call.- Specified by:
deactivateThrottlingin classEngine
-
trimUnreferencedTranslogFiles
public void trimUnreferencedTranslogFiles()
Description copied from class:Enginechecks and removes translog files that no longer need to be retained. SeeTranslogDeletionPolicyfor details- Specified by:
trimUnreferencedTranslogFilesin classEngine
-
shouldRollTranslogGeneration
public boolean shouldRollTranslogGeneration()
Description copied from class:EngineTests 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.- Specified by:
shouldRollTranslogGenerationin classEngine- Returns:
trueif the current generation should be rolled to a new generation
-
rollTranslogGeneration
public void rollTranslogGeneration()
Description copied from class:EngineRolls the translog generation and cleans unneeded.- Specified by:
rollTranslogGenerationin classEngine
-
restoreLocalHistoryFromTranslog
public int restoreLocalHistoryFromTranslog(Engine.TranslogRecoveryRunner translogRecoveryRunner)
Description copied from class:EngineThis method replays translog to restore the Lucene index which might be reverted previously. This ensures that all acknowledged writes are restored correctly when this engine is promoted.- Specified by:
restoreLocalHistoryFromTranslogin classEngine- Returns:
- the number of translog operations have been recovered
-
fillSeqNoGaps
public int fillSeqNoGaps(long primaryTerm)
Description copied from class:EngineFills up the local checkpoints history with no-ops until the local checkpoint and the max seen sequence ID are identical.- Specified by:
fillSeqNoGapsin classEngine- Parameters:
primaryTerm- the shards primary term this engine was created for- Returns:
- the number of no-ops added
-
recoverFromTranslog
public Engine recoverFromTranslog(Engine.TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo)
Description copied from class:EnginePerforms recovery from the transaction log up torecoverUpToSeqNo(inclusive). This operation will close the engine if the recovery fails.- Specified by:
recoverFromTranslogin classEngine- Parameters:
translogRecoveryRunner- the translog recovery runnerrecoverUpToSeqNo- the upper bound, inclusive, of sequence number to be recovered
-
skipTranslogRecovery
public void skipTranslogRecovery()
Description copied from class:EngineDo not replay translog operations, but make the engine be ready.- Specified by:
skipTranslogRecoveryin classEngine
-
trimOperationsFromTranslog
public void trimOperationsFromTranslog(long belowTerm, long aboveSeqNo)Description copied from class:EngineTrims translog for terms belowbelowTermand seq# aboveaboveSeqNo- Specified by:
trimOperationsFromTranslogin classEngine- See Also:
Translog.trimOperations(long, long)
-
maybePruneDeletes
public void maybePruneDeletes()
Description copied from class:EngineTries to prune buffered deletes from the version map.- Specified by:
maybePruneDeletesin classEngine
-
docStats
public DocsStats docStats()
Description copied from class:EngineReturns theDocsStatsfor this engine
-
updateMaxUnsafeAutoIdTimestamp
public void updateMaxUnsafeAutoIdTimestamp(long newTimestamp)
Description copied from class:EngineForces this engine to advance its max_unsafe_auto_id_timestamp marker to at least the given timestamp. The engine will disable optimization for all append-only whose timestamp at mostnewTimestamp.- Specified by:
updateMaxUnsafeAutoIdTimestampin classEngine
-
reinitializeMaxSeqNoOfUpdatesOrDeletes
public void reinitializeMaxSeqNoOfUpdatesOrDeletes()
Description copied from class:EngineA primary shard calls this method to re-initialize the max_seq_no_of_updates marker using the max_seq_no from Lucene index and translog before replaying the local translog in its local recovery.- Specified by:
reinitializeMaxSeqNoOfUpdatesOrDeletesin classEngine
-
processReaders
protected void processReaders(org.apache.lucene.index.IndexReader reader, org.apache.lucene.index.IndexReader previousReader)
-
refreshNeeded
public boolean refreshNeeded()
- Overrides:
refreshNeededin classEngine
-
-