idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
1,100
private void compactEntry ( long index , Segment segment , Segment compactSegment ) { compactSegment . skip ( 1 ) ; LOGGER . trace ( "Compacted entry {} from segment {}" , index , segment . descriptor ( ) . id ( ) ) ; }
Compacts an entry from the given segment .
1,101
private boolean isLive ( long index , Segment segment , OffsetPredicate predicate ) { long offset = segment . offset ( index ) ; return offset != - 1 && predicate . test ( offset ) ; }
Returns a boolean value indicating whether the given index is release .
1,102
private void mergeReleased ( List < Segment > segments , List < OffsetPredicate > predicates , Segment compactSegment ) { for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { mergeReleasedEntries ( segments . get ( i ) , predicates . get ( i ) , compactSegment ) ; } }
Updates the new compact segment with entries that were released during compaction .
1,103
private void mergeReleasedEntries ( Segment segment , OffsetPredicate predicate , Segment compactSegment ) { for ( long i = segment . firstIndex ( ) ; i <= segment . lastIndex ( ) ; i ++ ) { long offset = segment . offset ( i ) ; if ( offset != - 1 && ! predicate . test ( offset ) ) { compactSegment . release ( i ) ; }...
Updates the new compact segment with entries that were released in the given segment during compaction .
1,104
private void deleteGroup ( List < Segment > group ) { for ( Segment oldSegment : group ) { oldSegment . close ( ) ; oldSegment . delete ( ) ; } }
Completes compaction by deleting old segments .
1,105
public ClientConnection reset ( Address leader , Collection < Address > servers ) { selector . reset ( leader , servers ) ; return this ; }
Resets the client connection .
1,106
private < T extends Request , U > void sendRequest ( T request , BiFunction < Request , Connection , CompletableFuture < U > > sender , Connection connection , Throwable error , CompletableFuture < U > future ) { if ( open ) { if ( error == null ) { if ( connection != null ) { LOGGER . trace ( "{} - Sending {}" , id , ...
Sends the given request attempt to the cluster via the given connection if connected .
1,107
private void connect ( CompletableFuture < Connection > future ) { if ( ! selector . hasNext ( ) ) { LOGGER . debug ( "{} - Failed to connect to the cluster" , id ) ; future . complete ( null ) ; } else { Address address = selector . next ( ) ; LOGGER . debug ( "{} - Connecting to {}" , id , address ) ; client . connec...
Attempts to connect to the cluster .
1,108
private void handleConnection ( Address address , Connection connection , Throwable error , CompletableFuture < Connection > future ) { if ( open ) { if ( error == null ) { setupConnection ( address , connection , future ) ; } else { LOGGER . debug ( "{} - Failed to connect! Reason: {}" , id , error ) ; connect ( futur...
Handles a connection to a server .
1,109
private void handleConnectResponse ( ConnectResponse response , Throwable error , CompletableFuture < Connection > future ) { if ( open ) { if ( error == null ) { LOGGER . trace ( "{} - Received {}" , id , response ) ; if ( response . status ( ) == Response . Status . OK ) { selector . reset ( response . leader ( ) , r...
Handles a connect response .
1,110
private Iterable < Segment > getCompactableSegments ( Storage storage , SegmentManager manager ) { List < Segment > segments = new ArrayList < > ( manager . segments ( ) . size ( ) ) ; Iterator < Segment > iterator = manager . segments ( ) . iterator ( ) ; Segment segment = iterator . next ( ) ; while ( iterator . hasN...
Returns a list of compactable segments .
1,111
public void init ( StateMachineExecutor executor ) { this . executor = Assert . notNull ( executor , "executor" ) ; this . context = executor . context ( ) ; this . clock = context . clock ( ) ; this . sessions = context . sessions ( ) ; if ( this instanceof SessionListener ) { executor . context ( ) . sessions ( ) . a...
Initializes the state machine .
1,112
private void registerOperations ( ) { Class < ? > type = getClass ( ) ; for ( Method method : type . getMethods ( ) ) { if ( isOperationMethod ( method ) ) { registerMethod ( method ) ; } } }
Registers operations for the class .
1,113
private boolean isOperationMethod ( Method method ) { Class < ? > [ ] paramTypes = method . getParameterTypes ( ) ; return paramTypes . length == 1 && paramTypes [ 0 ] == Commit . class ; }
Returns a boolean value indicating whether the given method is an operation method .
1,114
private void registerMethod ( Method method ) { Type genericType = method . getGenericParameterTypes ( ) [ 0 ] ; Class < ? > argumentType = resolveArgument ( genericType ) ; if ( argumentType != null && Operation . class . isAssignableFrom ( argumentType ) ) { registerMethod ( argumentType , method ) ; } }
Registers an operation for the given method .
1,115
private Class < ? > resolveArgument ( Type type ) { if ( type instanceof ParameterizedType ) { ParameterizedType paramType = ( ParameterizedType ) type ; return resolveClass ( paramType . getActualTypeArguments ( ) [ 0 ] ) ; } else if ( type instanceof TypeVariable ) { return resolveClass ( type ) ; } else if ( type in...
Resolves the generic argument for the given type .
1,116
private Class < ? > resolveClass ( Type type ) { if ( type instanceof Class ) { return ( Class < ? > ) type ; } else if ( type instanceof ParameterizedType ) { return resolveClass ( ( ( ParameterizedType ) type ) . getRawType ( ) ) ; } else if ( type instanceof WildcardType ) { Type [ ] bounds = ( ( WildcardType ) type...
Resolves the generic class for the given type .
1,117
private void registerMethod ( Class < ? > type , Method method ) { Class < ? > returnType = method . getReturnType ( ) ; if ( returnType == void . class || returnType == Void . class ) { registerVoidMethod ( type , method ) ; } else { registerValueMethod ( type , method ) ; } }
Registers the given method for the given operation type .
1,118
@ SuppressWarnings ( "unchecked" ) private void registerVoidMethod ( Class type , Method method ) { executor . register ( type , wrapVoidMethod ( method ) ) ; }
Registers an operation with a void return value .
1,119
private Consumer wrapVoidMethod ( Method method ) { return c -> { try { method . invoke ( this , c ) ; } catch ( InvocationTargetException e ) { throw new CommandException ( e ) ; } catch ( IllegalAccessException e ) { throw new AssertionError ( e ) ; } } ; }
Wraps a void method .
1,120
@ SuppressWarnings ( "unchecked" ) private void registerValueMethod ( Class type , Method method ) { executor . register ( type , wrapValueMethod ( method ) ) ; }
Registers an operation with a non - void return value .
1,121
private Function wrapValueMethod ( Method method ) { return c -> { try { return method . invoke ( this , c ) ; } catch ( InvocationTargetException e ) { throw new CommandException ( e ) ; } catch ( IllegalAccessException e ) { throw new AssertionError ( e ) ; } } ; }
Wraps a value method .
1,122
public long id ( ) { return Long . valueOf ( file . getName ( ) . substring ( file . getName ( ) . lastIndexOf ( PART_SEPARATOR , file . getName ( ) . lastIndexOf ( PART_SEPARATOR ) - 1 ) + 1 , file . getName ( ) . lastIndexOf ( PART_SEPARATOR ) ) ) ; }
Returns the segment identifier .
1,123
public long version ( ) { return Long . valueOf ( file . getName ( ) . substring ( file . getName ( ) . lastIndexOf ( PART_SEPARATOR ) + 1 , file . getName ( ) . lastIndexOf ( EXTENSION_SEPARATOR ) ) ) ; }
Returns the segment version .
1,124
private void setState ( State state ) { if ( this . state != state ) { this . state = state ; LOGGER . debug ( "State changed: {}" , state ) ; changeListeners . forEach ( l -> l . accept ( state ) ) ; } }
Updates the client state .
1,125
private ClientSession newSession ( ) { ClientSession session = new ClientSession ( clientId , transport . client ( ) , selector , ioContext , connectionStrategy , sessionTimeout , unstabilityTimeout ) ; if ( changeListener != null ) changeListener . close ( ) ; changeListener = session . onStateChange ( this :: onState...
Creates a new child session .
1,126
private void onStateChange ( Session . State state ) { switch ( state ) { case OPEN : setState ( State . CONNECTED ) ; break ; case UNSTABLE : setState ( State . SUSPENDED ) ; break ; case STALE : setState ( State . SUSPENDED ) ; this . close ( ) ; break ; case EXPIRED : setState ( State . SUSPENDED ) ; recoveryStrateg...
Handles a session state change .
1,127
public synchronized CompletableFuture < Void > kill ( ) { if ( state == State . CLOSED ) return CompletableFuture . completedFuture ( null ) ; if ( closeFuture == null ) { closeFuture = session . kill ( ) . whenComplete ( ( result , error ) -> { setState ( State . CLOSED ) ; CompletableFuture . runAsync ( ( ) -> { ioCo...
Kills the client .
1,128
public static void main ( String [ ] args ) throws Exception { if ( args . length < 1 ) throw new IllegalArgumentException ( "must supply a set of host:port tuples" ) ; List < Address > members = new ArrayList < > ( ) ; for ( String arg : args ) { String [ ] parts = arg . split ( ":" ) ; members . add ( new Address ( p...
Starts the client .
1,129
private static void recursiveSet ( CopycatClient client ) { client . submit ( new SetCommand ( UUID . randomUUID ( ) . toString ( ) ) ) . whenComplete ( ( result , error ) -> { client . context ( ) . schedule ( Duration . ofSeconds ( 5 ) , ( ) -> recursiveSet ( client ) ) ; } ) ; }
Recursively sets state machine values .
1,130
void init ( long index , Instant instant , ServerStateMachineContext . Type type ) { context . update ( index , instant , type ) ; }
Initializes the execution of a task .
1,131
@ SuppressWarnings ( "unchecked" ) < T extends Operation < U > , U > U executeOperation ( Commit commit ) { if ( commit . operation ( ) instanceof NoOpCommand ) { commit . close ( ) ; return null ; } Function function = operations . get ( commit . type ( ) ) ; if ( function == null ) { for ( Map . Entry < Class , Funct...
Executes an operation .
1,132
private long findAfter ( long offset ) { if ( size == 0 ) { return - 1 ; } int low = 0 ; int high = size - 1 ; while ( low <= high ) { int mid = low + ( ( high - low ) / 2 ) ; long i = buffer . readLong ( mid * ENTRY_SIZE ) ; if ( i < offset ) { low = mid + 1 ; } else if ( i > offset ) { high = mid - 1 ; } else { retur...
Returns the real offset for the given relative offset .
1,133
public long index ( ) { return Long . valueOf ( file . getName ( ) . substring ( file . getName ( ) . lastIndexOf ( PART_SEPARATOR , file . getName ( ) . lastIndexOf ( PART_SEPARATOR ) - 1 ) + 1 , file . getName ( ) . lastIndexOf ( PART_SEPARATOR ) ) ) ; }
Returns the snapshot index .
1,134
public AddressSelector reset ( ) { if ( selectionsIterator != null ) { this . selections = strategy . selectConnections ( leader , new ArrayList < > ( servers ) ) ; this . selectionsIterator = null ; } return this ; }
Resets the addresses .
1,135
public AddressSelector reset ( Address leader , Collection < Address > servers ) { if ( changed ( leader , servers ) ) { this . leader = leader ; this . servers = servers ; this . selections = strategy . selectConnections ( leader , new ArrayList < > ( servers ) ) ; this . selectionsIterator = null ; } return this ; }
Resets the connection addresses .
1,136
private boolean matches ( Collection < Address > left , Collection < Address > right ) { if ( left . size ( ) != right . size ( ) ) return false ; for ( Address address : left ) { if ( ! right . contains ( address ) ) { return false ; } } return true ; }
Returns a boolean value indicating whether the servers in the first list match the servers in the second list .
1,137
public Compactor withDefaultCompactionMode ( Compaction . Mode mode ) { Assert . notNull ( mode , "mode" ) ; Assert . argNot ( mode , mode == Compaction . Mode . DEFAULT , "DEFAULT cannot be the default compaction mode" ) ; this . defaultCompactionMode = mode ; return this ; }
Sets the default compaction mode .
1,138
public Compactor minorIndex ( long index ) { this . minorIndex = Math . max ( this . minorIndex , index ) ; Segment segment = segments . segment ( minorIndex ) ; if ( segment != null ) { compactIndex = segment . firstIndex ( ) ; } return this ; }
Sets the maximum compaction index for minor compaction .
1,139
private synchronized CompletableFuture < Void > compact ( Compaction compaction , CompletableFuture < Void > future , ThreadContext context ) { CompactionManager manager = compaction . manager ( this ) ; AtomicInteger counter = new AtomicInteger ( ) ; Collection < CompactionTask > tasks = manager . buildTasks ( storage...
Compacts the log .
1,140
void reset ( OperationEntry < ? > entry , ServerSessionContext session , long timestamp ) { if ( references . compareAndSet ( 0 , 1 ) ) { this . index = entry . getIndex ( ) ; this . session = session ; this . instant = Instant . ofEpochMilli ( timestamp ) ; this . operation = entry . getOperation ( ) ; session . acqui...
Resets the commit .
1,141
private void cleanup ( ) { if ( operation instanceof Command && log . isOpen ( ) ) { try { log . release ( index ) ; } catch ( IllegalStateException e ) { } } session . release ( ) ; index = 0 ; session = null ; instant = null ; operation = null ; pool . release ( this ) ; }
Cleans up the commit .
1,142
private CompletableFuture < Void > listen ( ) { CompletableFuture < Void > future = new CompletableFuture < > ( ) ; context . getThreadContext ( ) . executor ( ) . execute ( ( ) -> { internalServer . listen ( cluster ( ) . member ( ) . serverAddress ( ) , context :: connectServer ) . whenComplete ( ( internalResult , i...
Starts listening the server .
1,143
private void buildIndex ( ) { long position = buffer . mark ( ) . position ( ) ; int length = buffer . readInt ( ) ; while ( length != 0 ) { buffer . read ( memory . clear ( ) . limit ( length ) ) ; memory . flip ( ) ; long checksum = memory . readUnsignedInt ( ) ; long offset = memory . readLong ( ) ; Long term = memo...
Builds the index from the segment bytes .
1,144
public long lastIndex ( ) { assertSegmentOpen ( ) ; return ! isEmpty ( ) ? offsetIndex . lastOffset ( ) + descriptor . index ( ) + skip : descriptor . index ( ) - 1 ; }
Returns the index of the last entry in the segment .
1,145
private void checkRange ( long index ) { Assert . indexNot ( isEmpty ( ) , "segment is empty" ) ; Assert . indexNot ( index < firstIndex ( ) , index + " is less than the first index in the segment" ) ; Assert . indexNot ( index > lastIndex ( ) , index + " is greater than the last index in the segment" ) ; }
Checks the range of the given index .
1,146
public long append ( Entry entry ) { Assert . notNull ( entry , "entry" ) ; Assert . stateNot ( isFull ( ) , "segment is full" ) ; long index = nextIndex ( ) ; Assert . index ( index == entry . getIndex ( ) , "inconsistent index: %s" , entry . getIndex ( ) ) ; long offset = relativeOffset ( index ) ; long term = entry ...
Commits an entry to the segment .
1,147
public long term ( long index ) { assertSegmentOpen ( ) ; checkRange ( index ) ; long offset = relativeOffset ( index ) ; return termIndex . lookup ( offset ) ; }
Reads the term for the entry at the given index .
1,148
public synchronized < T extends Entry > T get ( long index ) { assertSegmentOpen ( ) ; checkRange ( index ) ; long offset = relativeOffset ( index ) ; long position = offsetIndex . position ( offset ) ; if ( position != - 1 ) { int length = buffer . readInt ( position ) ; try ( Buffer slice = buffer . slice ( position ...
Reads the entry at the given index .
1,149
public boolean contains ( long index ) { assertSegmentOpen ( ) ; if ( ! validIndex ( index ) ) return false ; long offset = relativeOffset ( index ) ; return offsetIndex . contains ( offset ) ; }
Returns a boolean value indicating whether the entry at the given index is active .
1,150
public boolean release ( long index ) { assertSegmentOpen ( ) ; long offset = offsetIndex . find ( relativeOffset ( index ) ) ; return offset != - 1 && offsetPredicate . release ( offset ) ; }
Releases an entry from the segment .
1,151
public Segment truncate ( long index ) { assertSegmentOpen ( ) ; Assert . index ( index >= manager . commitIndex ( ) , "cannot truncate committed index" ) ; long offset = relativeOffset ( index ) ; long lastOffset = offsetIndex . lastOffset ( ) ; long diff = Math . abs ( lastOffset - offset ) ; skip = Math . max ( skip...
Truncates entries after the given index .
1,152
void update ( long index , Instant instant , Type type ) { this . index = index ; this . type = type ; clock . set ( instant ) ; }
Updates the state machine context .
1,153
void commit ( ) { long index = this . index ; for ( ServerSessionContext session : sessions . sessions . values ( ) ) { session . commit ( index ) ; } }
Commits the state machine index .
1,154
public Listener < CopycatServer . State > onStateChange ( Consumer < CopycatServer . State > listener ) { return stateChangeListeners . add ( listener ) ; }
Registers a state change listener .
1,155
ServerContext setGlobalIndex ( long globalIndex ) { Assert . argNot ( globalIndex < 0 , "global index must be positive" ) ; this . globalIndex = Math . max ( this . globalIndex , globalIndex ) ; log . compactor ( ) . majorIndex ( this . globalIndex - 1 ) ; return this ; }
Sets the global index .
1,156
ServerContext reset ( ) { if ( log != null ) { log . close ( ) ; storage . deleteLog ( name ) ; } if ( snapshot != null ) { snapshot . close ( ) ; storage . deleteSnapshotStore ( name ) ; } log = storage . openLog ( name ) ; snapshot = storage . openSnapshotStore ( name ) ; StateMachine stateMachine = stateMachineFacto...
Resets the state log .
1,157
public void connectClient ( Connection connection ) { threadContext . checkThread ( ) ; connection . handler ( RegisterRequest . class , ( Function < RegisterRequest , CompletableFuture < RegisterResponse > > ) request -> state . register ( request ) ) ; connection . handler ( ConnectRequest . class , ( Function < Conn...
Handles a connection from a client .
1,158
public void connectServer ( Connection connection ) { threadContext . checkThread ( ) ; connection . handler ( RegisterRequest . class , ( Function < RegisterRequest , CompletableFuture < RegisterResponse > > ) request -> state . register ( request ) ) ; connection . handler ( ConnectRequest . class , ( Function < Conn...
Handles a connection from another server .
1,159
public void delete ( ) { storage . deleteLog ( name ) ; storage . deleteSnapshotStore ( name ) ; storage . deleteMetaStore ( name ) ; }
Deletes the server context .
1,160
public CompletableFuture < Connection > getConnection ( Address address ) { Connection connection = connections . get ( address ) ; return connection == null ? createConnection ( address ) : CompletableFuture . completedFuture ( connection ) ; }
Returns the connection for the given member .
1,161
public void resetConnection ( Address address ) { Connection connection = connections . remove ( address ) ; if ( connection != null ) { connection . close ( ) ; } }
Resets the connection to the given address .
1,162
private CompletableFuture < Connection > createConnection ( Address address ) { return connectionFutures . computeIfAbsent ( address , a -> { CompletableFuture < Connection > future = client . connect ( address ) . thenApply ( connection -> { connection . onClose ( c -> connections . remove ( address , c ) ) ; connecti...
Creates a connection for the given member .
1,163
public CompletableFuture < Void > close ( ) { CompletableFuture [ ] futures = new CompletableFuture [ connections . size ( ) ] ; for ( CompletableFuture < Connection > future : this . connectionFutures . values ( ) ) { future . cancel ( false ) ; } int i = 0 ; for ( Connection connection : connections . values ( ) ) { ...
Closes the connection manager .
1,164
private void compactEntries ( Segment segment , Segment compactSegment ) { for ( long i = segment . firstIndex ( ) ; i <= segment . lastIndex ( ) ; i ++ ) { checkEntry ( i , segment , compactSegment ) ; } }
Compacts entries from the given segment rewriting them to the compact segment .
1,165
private void checkEntry ( long index , Segment segment , Segment compactSegment ) { try ( Entry entry = segment . get ( index ) ) { if ( entry != null ) { checkEntry ( index , entry , segment , compactSegment ) ; } else { compactSegment . skip ( 1 ) ; } } }
Compacts the entry at the given index .
1,166
private void checkEntry ( long index , Entry entry , Segment segment , Segment compactSegment ) { Compaction . Mode mode = entry . getCompactionMode ( ) ; if ( mode == Compaction . Mode . DEFAULT ) { mode = defaultCompactionMode ; } switch ( mode ) { case SNAPSHOT : if ( index <= snapshotIndex && ! segment . isLive ( i...
Compacts a command entry from a segment .
1,167
private void transferEntry ( long index , Entry entry , Segment compactSegment ) { compactSegment . append ( entry ) ; if ( ! segment . isLive ( index ) ) { compactSegment . release ( index ) ; } }
Transfers an entry to the given compact segment .
1,168
private void mergeReleasedEntries ( Segment segment , Segment compactSegment ) { for ( long i = segment . firstIndex ( ) ; i <= segment . lastIndex ( ) ; i ++ ) { if ( ! segment . isLive ( i ) ) { compactSegment . release ( i ) ; } } }
Updates the new compact segment with entries that were released from the given segment during compaction .
1,169
private void open ( ) { for ( Snapshot snapshot : loadSnapshots ( ) ) { snapshots . put ( snapshot . index ( ) , snapshot ) ; } if ( ! snapshots . isEmpty ( ) ) { currentSnapshot = snapshots . lastEntry ( ) . getValue ( ) ; } }
Opens the snapshot manager .
1,170
private Snapshot createMemorySnapshot ( SnapshotDescriptor descriptor ) { HeapBuffer buffer = HeapBuffer . allocate ( SnapshotDescriptor . BYTES , Integer . MAX_VALUE ) ; Snapshot snapshot = new MemorySnapshot ( buffer , descriptor . copyTo ( buffer ) , this ) ; LOGGER . debug ( "Created memory snapshot: {}" , snapshot...
Creates a memory snapshot .
1,171
@ SuppressWarnings ( "unused" ) protected Entry getPrevEntry ( MemberState member ) { long prevIndex = Math . min ( member . getNextIndex ( ) - 1 , context . getLog ( ) . lastIndex ( ) ) ; while ( prevIndex > 0 ) { Entry entry = context . getLog ( ) . get ( prevIndex ) ; if ( entry != null ) { return entry ; } prevInde...
Gets the previous entry .
1,172
protected void sendAppendRequest ( Connection connection , MemberState member , AppendRequest request ) { long timestamp = System . nanoTime ( ) ; logger . trace ( "{} - Sending {} to {}" , context . getCluster ( ) . member ( ) . address ( ) , request , member . getMember ( ) . address ( ) ) ; connection . < AppendRequ...
Sends a commit message .
1,173
protected void updateNextIndex ( MemberState member , AppendRequest request ) { if ( ! request . entries ( ) . isEmpty ( ) ) { member . setNextIndex ( request . entries ( ) . get ( request . entries ( ) . size ( ) - 1 ) . getIndex ( ) + 1 ) ; } }
Updates the next index when the match index is updated .
1,174
protected void sendConfigureRequest ( Connection connection , MemberState member , ConfigureRequest request ) { logger . trace ( "{} - Sending {} to {}" , context . getCluster ( ) . member ( ) . address ( ) , request , member . getMember ( ) . serverAddress ( ) ) ; connection . < ConfigureRequest , ConfigureResponse > ...
Sends a configuration message .
1,175
protected void sendInstallRequest ( Connection connection , MemberState member , InstallRequest request ) { logger . trace ( "{} - Sending {} to {}" , context . getCluster ( ) . member ( ) . address ( ) , request , member . getMember ( ) . serverAddress ( ) ) ; connection . < InstallRequest , InstallResponse > sendAndR...
Sends a snapshot message .
1,176
protected void handleInstallRequestFailure ( MemberState member , InstallRequest request , Throwable error ) { failAttempt ( member , error ) ; }
Handles an install request failure .
1,177
protected void handleInstallResponseFailure ( MemberState member , InstallRequest request , Throwable error ) { member . setNextSnapshotIndex ( 0 ) . setNextSnapshotOffset ( 0 ) ; failAttempt ( member , error ) ; }
Handles an install response failure .
1,178
public EntryBuffer append ( Entry entry ) { int offset = offset ( entry . getIndex ( ) ) ; Entry oldEntry = buffer [ offset ] ; buffer [ offset ] = entry . acquire ( ) ; if ( oldEntry != null ) { oldEntry . release ( ) ; } return this ; }
Appends an entry to the buffer .
1,179
@ SuppressWarnings ( "unchecked" ) public < T extends Entry > T get ( long index ) { Entry entry = buffer [ offset ( index ) ] ; return entry != null && entry . getIndex ( ) == index ? ( T ) entry . acquire ( ) : null ; }
Looks up an entry in the buffer .
1,180
public EntryBuffer clear ( ) { for ( int i = 0 ; i < buffer . length ; i ++ ) { buffer [ i ] = null ; } return this ; }
Clears the buffer and resets the index to the given index .
1,181
private int offset ( long index ) { int offset = ( int ) ( index % buffer . length ) ; if ( offset < 0 ) { offset += buffer . length ; } return offset ; }
Returns the buffer index for the given offset .
1,182
public Listener < Session . State > onStateChange ( Consumer < Session . State > callback ) { Listener < Session . State > listener = new Listener < Session . State > ( ) { public void accept ( Session . State state ) { callback . accept ( state ) ; } public void close ( ) { changeListeners . remove ( this ) ; } } ; ch...
Registers a state change listener on the session manager .
1,183
public synchronized long term ( ) { Map . Entry < Long , Long > entry = terms . lastEntry ( ) ; return entry != null ? entry . getValue ( ) : 0 ; }
Returns the highest term in the index .
1,184
public synchronized void index ( long offset , long term ) { if ( lookup ( offset ) != term ) { terms . put ( offset , term ) ; } }
Indexes the given offset with the given term .
1,185
public synchronized long lookup ( long offset ) { Map . Entry < Long , Long > entry = terms . floorEntry ( offset ) ; return entry != null ? entry . getValue ( ) : 0 ; }
Looks up the term for the given offset .
1,186
public boolean release ( long offset ) { Assert . argNot ( offset < 0 , "offset must be positive" ) ; if ( bits . size ( ) <= offset ) { while ( bits . size ( ) <= offset ) { bits . resize ( bits . size ( ) * 2 ) ; } } return bits . set ( offset ) ; }
Releases an offset from the segment .
1,187
public < T > CompletableFuture < T > submit ( Operation < T > operation ) { if ( operation instanceof Query ) { return submit ( ( Query < T > ) operation ) ; } else if ( operation instanceof Command ) { return submit ( ( Command < T > ) operation ) ; } else { throw new UnsupportedOperationException ( "unknown operation...
Submits an operation to the session .
1,188
public < T > CompletableFuture < T > submit ( Command < T > command ) { State state = state ( ) ; if ( state == State . CLOSED || state == State . EXPIRED ) { return Futures . exceptionalFuture ( new ClosedSessionException ( "session closed" ) ) ; } return submitter . submit ( command ) ; }
Submits a command to the session .
1,189
public < T > CompletableFuture < T > submit ( Query < T > query ) { State state = state ( ) ; if ( state == State . CLOSED || state == State . EXPIRED ) { return Futures . exceptionalFuture ( new ClosedSessionException ( "session closed" ) ) ; } return submitter . submit ( query ) ; }
Submits a query to the session .
1,190
public CompletableFuture < Void > kill ( ) { return submitter . close ( ) . thenCompose ( v -> listener . close ( ) ) . thenCompose ( v -> manager . kill ( ) ) . thenCompose ( v -> connection . close ( ) ) ; }
Kills the session .
1,191
private long calculateLastCompleted ( long index ) { long lastCompleted = index ; for ( ServerSessionContext session : executor . context ( ) . sessions ( ) . sessions . values ( ) ) { lastCompleted = Math . min ( lastCompleted , session . getLastCompleted ( ) ) ; } return lastCompleted ; }
Calculates the last completed session event index .
1,192
private void setLastCompleted ( long lastCompleted ) { if ( ! log . isOpen ( ) ) return ; this . lastCompleted = Math . max ( this . lastCompleted , lastCompleted ) ; log . compactor ( ) . minorIndex ( this . lastCompleted ) ; completeSnapshot ( ) ; }
Updates the last completed event index based on a commit at the given index .
1,193
private void keepAliveSession ( long index , long timestamp , long commandSequence , long eventIndex , ServerSessionContext session , CompletableFuture < Void > future , ThreadContext context ) { if ( ! log . isOpen ( ) ) { context . executor ( ) . execute ( ( ) -> future . completeExceptionally ( new IllegalStateExcep...
Applies a keep alive for a session .
1,194
private void sequenceCommand ( long sequence , ServerSessionContext session , CompletableFuture < Result > future , ThreadContext context ) { if ( ! log . isOpen ( ) ) { context . executor ( ) . execute ( ( ) -> future . completeExceptionally ( new IllegalStateException ( "log closed" ) ) ) ; return ; } Result result =...
Sequences a command according to the command sequence number .
1,195
private void executeCommand ( long index , long sequence , long timestamp , ServerCommit commit , ServerSessionContext session , CompletableFuture < Result > future , ThreadContext context ) { if ( ! log . isOpen ( ) ) { context . executor ( ) . execute ( ( ) -> future . completeExceptionally ( new IllegalStateExceptio...
Executes a state machine command .
1,196
private void executeQuery ( ServerCommit commit , ServerSessionContext session , CompletableFuture < Result > future , ThreadContext context ) { if ( ! log . isOpen ( ) ) { context . executor ( ) . execute ( ( ) -> future . completeExceptionally ( new IllegalStateException ( "log closed" ) ) ) ; return ; } if ( ! sessi...
Executes a state machine query .
1,197
private CompletableFuture < QueryResponse > query ( QueryEntry entry ) { Query . ConsistencyLevel consistency = entry . getQuery ( ) . consistency ( ) ; if ( consistency == null ) return queryLinearizable ( entry ) ; switch ( consistency ) { case SEQUENTIAL : return queryLocal ( entry ) ; case LINEARIZABLE_LEASE : retu...
Applies the given query entry to the state machine according to the query s consistency level .
1,198
private CompletableFuture < QueryResponse > sequenceAndApply ( QueryEntry entry ) { ServerSessionContext session = context . getStateMachine ( ) . executor ( ) . context ( ) . sessions ( ) . getSession ( entry . getSession ( ) ) ; if ( session == null ) { return CompletableFuture . completedFuture ( logResponse ( Query...
Sequences and applies the given query entry .
1,199
private void cancelAppendTimer ( ) { if ( appendTimer != null ) { LOGGER . trace ( "{} - Cancelling append timer" , context . getCluster ( ) . member ( ) . address ( ) ) ; appendTimer . cancel ( ) ; } }
Cancels the append timer .