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 , request ) ; sender . apply ( request , connection ) . whenComplete ( ( r , e ) -> { if ( e != null || r != null ) { handleResponse ( request , sender , connection , ( Response ) r , e , future ) ; } else { future . complete ( null ) ; } } ) ; } else { future . completeExceptionally ( new ConnectException ( "Failed to connect to the cluster" ) ) ; } } else { LOGGER . trace ( "{} - Resending {}: {}" , id , request , error ) ; resendRequest ( error , request , sender , connection , future ) ; } } }
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 . connect ( address ) . whenComplete ( ( c , e ) -> handleConnection ( address , c , e , future ) ) ; } }
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 ( future ) ; } } }
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 ( ) , response . members ( ) ) ; future . complete ( connection ) ; } else { connect ( future ) ; } } else { LOGGER . debug ( "{} - Failed to connect! Reason: {}" , id , error ) ; connect ( future ) ; } } }
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 . hasNext ( ) ) { Segment nextSegment = iterator . next ( ) ; if ( segment . isCompacted ( ) || ( segment . isFull ( ) && segment . lastIndex ( ) < compactor . minorIndex ( ) && nextSegment . firstIndex ( ) <= manager . commitIndex ( ) && ! nextSegment . isEmpty ( ) ) ) { double compactablePercentage = segment . releaseCount ( ) / ( double ) segment . count ( ) ; if ( compactablePercentage * segment . descriptor ( ) . version ( ) >= storage . compactionThreshold ( ) ) { segments . add ( segment ) ; } } segment = nextSegment ; } return segments ; }
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 ( ) . addListener ( ( SessionListener ) this ) ; } configure ( executor ) ; }
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 instanceof Class ) { TypeVariable < ? > [ ] typeParams = ( ( Class < ? > ) type ) . getTypeParameters ( ) ; return resolveClass ( typeParams [ 0 ] ) ; } return null ; }
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 ) . getUpperBounds ( ) ; if ( bounds . length > 0 ) { return ( Class < ? > ) bounds [ 0 ] ; } } return null ; }
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 :: onStateChange ) ; eventListeners . forEach ( l -> l . register ( session ) ) ; return session ; }
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 ) ; recoveryStrategy . recover ( this ) ; break ; case CLOSED : setState ( State . CLOSED ) ; break ; default : break ; } }
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 ( ( ) -> { ioContext . close ( ) ; eventContext . close ( ) ; transport . close ( ) ; } ) ; } ) ; } return closeFuture ; }
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 ( parts [ 0 ] , Integer . valueOf ( parts [ 1 ] ) ) ) ; } CopycatClient client = CopycatClient . builder ( ) . withTransport ( new NettyTransport ( ) ) . withConnectionStrategy ( ConnectionStrategies . FIBONACCI_BACKOFF ) . withRecoveryStrategy ( RecoveryStrategies . RECOVER ) . withServerSelectionStrategy ( ServerSelectionStrategies . LEADER ) . withSessionTimeout ( Duration . ofSeconds ( 15 ) ) . build ( ) ; client . serializer ( ) . register ( SetCommand . class , 1 ) ; client . serializer ( ) . register ( GetQuery . class , 2 ) ; client . serializer ( ) . register ( DeleteCommand . class , 3 ) ; client . connect ( members ) . join ( ) ; recursiveSet ( client ) ; while ( client . state ( ) != CopycatClient . State . CLOSED ) { try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { break ; } } }
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 , Function > entry : operations . entrySet ( ) ) { if ( entry . getKey ( ) . isAssignableFrom ( commit . type ( ) ) ) { function = entry . getValue ( ) ; break ; } } if ( function != null ) { operations . put ( commit . type ( ) , function ) ; } } if ( function == null ) { throw new IllegalStateException ( "unknown state machine operation: " + commit . type ( ) ) ; } else { try { return ( U ) function . apply ( commit ) ; } catch ( Exception e ) { LOGGER . warn ( "State machine operation failed: {}" , e ) ; throw new ApplicationException ( e , "An application error occurred" ) ; } } }
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 { return mid ; } } return ( low < high ) ? low + 1 : high + 1 ; }
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 , segments ) ; if ( ! tasks . isEmpty ( ) ) { LOGGER . info ( "Compacting log with compaction: {}" , compaction ) ; LOGGER . debug ( "Executing {} compaction task(s)" , tasks . size ( ) ) ; for ( CompactionTask task : tasks ) { LOGGER . debug ( "Executing {}" , task ) ; ThreadContext taskThread = new ThreadPoolContext ( executor , segments . serializer ( ) ) ; taskThread . execute ( task ) . whenComplete ( ( result , error ) -> { LOGGER . debug ( "{} complete" , task ) ; if ( counter . incrementAndGet ( ) == tasks . size ( ) ) { if ( context != null ) { context . executor ( ) . execute ( ( ) -> future . complete ( null ) ) ; } else { future . complete ( null ) ; } } } ) ; } } else { future . complete ( null ) ; } return future ; }
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 . acquire ( ) ; references . set ( 1 ) ; } else { throw new IllegalStateException ( "Cannot recycle commit with " + references . get ( ) + " references" ) ; } }
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 , internalError ) -> { if ( internalError == null ) { if ( clientServer != null ) { clientServer . listen ( cluster ( ) . member ( ) . clientAddress ( ) , context :: connectClient ) . whenComplete ( ( clientResult , clientError ) -> { started = true ; future . complete ( null ) ; } ) ; } else { started = true ; future . complete ( null ) ; } } else { future . completeExceptionally ( internalError ) ; } } ) ; } ) ; return future ; }
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 = memory . readBoolean ( ) ? memory . readLong ( ) : null ; int entryPosition = ( int ) memory . position ( ) ; int entryLength = length - entryPosition ; Checksum crc32 = new CRC32 ( ) ; crc32 . update ( memory . array ( ) , entryPosition , entryLength ) ; if ( checksum == crc32 . getValue ( ) ) { if ( term != null ) { termIndex . index ( offset , term ) ; } offsetIndex . index ( offset , position ) ; } else { break ; } position = buffer . position ( ) ; length = buffer . mark ( ) . readInt ( ) ; } buffer . reset ( ) ; }
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 . getTerm ( ) ; long lastTerm = termIndex . term ( ) ; Assert . arg ( term > 0 && term >= lastTerm , "term must be monotonically increasing" ) ; long position = buffer . position ( ) ; boolean skipTerm = term == lastTerm ; int headerLength = INTEGER + LONG + BOOLEAN + ( skipTerm ? 0 : LONG ) ; memory . clear ( ) . skip ( headerLength ) ; serializer . writeObject ( entry , memory ) ; memory . flip ( ) ; int totalLength = ( int ) memory . limit ( ) ; int entryLength = totalLength - headerLength ; entry . setSize ( totalLength ) ; Checksum crc32 = new CRC32 ( ) ; crc32 . update ( memory . array ( ) , headerLength , entryLength ) ; long checksum = crc32 . getValue ( ) ; memory . rewind ( ) . writeUnsignedInt ( checksum ) . writeLong ( offset ) ; if ( skipTerm ) { memory . writeBoolean ( false ) ; } else { memory . writeBoolean ( true ) . writeLong ( term ) ; } buffer . writeInt ( totalLength ) . write ( memory . rewind ( ) ) ; offsetIndex . index ( offset , position ) ; if ( term > lastTerm ) { termIndex . index ( offset , term ) ; } skip = 0 ; return index ; }
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 + INTEGER , length ) ) { slice . read ( memory . clear ( ) . limit ( length ) ) ; memory . flip ( ) ; } long checksum = memory . readUnsignedInt ( ) ; long entryOffset = memory . readLong ( ) ; Assert . state ( entryOffset == offset , "inconsistent index: %s" , index ) ; if ( memory . readBoolean ( ) ) { memory . skip ( LONG ) ; } int entryPosition = ( int ) memory . position ( ) ; int entryLength = length - entryPosition ; Checksum crc32 = new CRC32 ( ) ; crc32 . update ( memory . array ( ) , entryPosition , entryLength ) ; if ( checksum == crc32 . getValue ( ) ) { T entry = serializer . readObject ( memory ) ; entry . setIndex ( index ) . setTerm ( termIndex . lookup ( offset ) ) . setSize ( length ) ; return entry ; } } return null ; }
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 - diff , 0 ) ; if ( offset < lastOffset ) { long position = offsetIndex . truncate ( offset ) ; buffer . position ( position ) . zero ( position ) . flush ( ) ; termIndex . truncate ( offset ) ; } return this ; }
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 = stateMachineFactory . get ( ) ; if ( stateMachine instanceof Snapshottable ) { log . compactor ( ) . withDefaultCompactionMode ( Compaction . Mode . SNAPSHOT ) ; } else { log . compactor ( ) . withDefaultCompactionMode ( Compaction . Mode . SEQUENTIAL ) ; } this . stateMachine = new ServerStateMachine ( stateMachine , this , stateContext ) ; return this ; }
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 < ConnectRequest , CompletableFuture < ConnectResponse > > ) request -> state . connect ( request , connection ) ) ; connection . handler ( KeepAliveRequest . class , ( Function < KeepAliveRequest , CompletableFuture < KeepAliveResponse > > ) request -> state . keepAlive ( request ) ) ; connection . handler ( UnregisterRequest . class , ( Function < UnregisterRequest , CompletableFuture < UnregisterResponse > > ) request -> state . unregister ( request ) ) ; connection . handler ( ResetRequest . class , ( Consumer < ResetRequest > ) request -> state . reset ( request ) ) ; connection . handler ( CommandRequest . class , ( Function < CommandRequest , CompletableFuture < CommandResponse > > ) request -> state . command ( request ) ) ; connection . handler ( QueryRequest . class , ( Function < QueryRequest , CompletableFuture < QueryResponse > > ) request -> state . query ( request ) ) ; connection . onClose ( stateMachine . executor ( ) . context ( ) . sessions ( ) :: unregisterConnection ) ; }
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 < ConnectRequest , CompletableFuture < ConnectResponse > > ) request -> state . connect ( request , connection ) ) ; connection . handler ( KeepAliveRequest . class , ( Function < KeepAliveRequest , CompletableFuture < KeepAliveResponse > > ) request -> state . keepAlive ( request ) ) ; connection . handler ( UnregisterRequest . class , ( Function < UnregisterRequest , CompletableFuture < UnregisterResponse > > ) request -> state . unregister ( request ) ) ; connection . handler ( ResetRequest . class , ( Consumer < ResetRequest > ) request -> state . reset ( request ) ) ; connection . handler ( ConfigureRequest . class , ( Function < ConfigureRequest , CompletableFuture < ConfigureResponse > > ) request -> state . configure ( request ) ) ; connection . handler ( InstallRequest . class , ( Function < InstallRequest , CompletableFuture < InstallResponse > > ) request -> state . install ( request ) ) ; connection . handler ( JoinRequest . class , ( Function < JoinRequest , CompletableFuture < JoinResponse > > ) request -> state . join ( request ) ) ; connection . handler ( ReconfigureRequest . class , ( Function < ReconfigureRequest , CompletableFuture < ReconfigureResponse > > ) request -> state . reconfigure ( request ) ) ; connection . handler ( LeaveRequest . class , ( Function < LeaveRequest , CompletableFuture < LeaveResponse > > ) request -> state . leave ( request ) ) ; connection . handler ( AppendRequest . class , ( Function < AppendRequest , CompletableFuture < AppendResponse > > ) request -> state . append ( request ) ) ; connection . handler ( PollRequest . class , ( Function < PollRequest , CompletableFuture < PollResponse > > ) request -> state . poll ( request ) ) ; connection . handler ( VoteRequest . class , ( Function < VoteRequest , CompletableFuture < VoteResponse > > ) request -> state . vote ( request ) ) ; connection . handler ( CommandRequest . class , ( Function < CommandRequest , CompletableFuture < CommandResponse > > ) request -> state . command ( request ) ) ; connection . handler ( QueryRequest . class , ( Function < QueryRequest , CompletableFuture < QueryResponse > > ) request -> state . query ( request ) ) ; connection . onClose ( stateMachine . executor ( ) . context ( ) . sessions ( ) :: unregisterConnection ) ; }
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 ) ) ; connections . put ( address , connection ) ; return connection ; } ) ; future . whenComplete ( ( connection , error ) -> connectionFutures . remove ( address ) ) ; return future ; } ) ; }
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 ( ) ) { futures [ i ++ ] = connection . close ( ) ; } return CompletableFuture . allOf ( futures ) ; }
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 ( index ) ) { compactEntry ( index , segment , compactSegment ) ; } else { transferEntry ( index , entry , compactSegment ) ; } break ; case RELEASE : case QUORUM : if ( ! segment . isLive ( index ) ) { compactEntry ( index , segment , compactSegment ) ; } else { transferEntry ( index , entry , compactSegment ) ; } break ; case FULL : if ( index <= compactIndex && ! segment . isLive ( index ) ) { compactEntry ( index , segment , compactSegment ) ; } else { transferEntry ( index , entry , compactSegment ) ; } break ; case SEQUENTIAL : case EXPIRING : case TOMBSTONE : case UNKNOWN : transferEntry ( index , entry , compactSegment ) ; break ; default : break ; } }
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 ) ; return 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 ; } prevIndex -- ; } return null ; }
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 . < AppendRequest , AppendResponse > sendAndReceive ( request ) . whenComplete ( ( response , error ) -> { context . checkThread ( ) ; if ( ! request . entries ( ) . isEmpty ( ) ) { member . completeAppend ( System . nanoTime ( ) - timestamp ) ; } else { member . completeAppend ( ) ; } if ( open ) { if ( error == null ) { logger . trace ( "{} - Received {} from {}" , context . getCluster ( ) . member ( ) . address ( ) , response , member . getMember ( ) . address ( ) ) ; handleAppendResponse ( member , request , response ) ; } else { handleAppendResponseFailure ( member , request , error ) ; } } } ) ; updateNextIndex ( member , request ) ; if ( ! request . entries ( ) . isEmpty ( ) && hasMoreEntries ( member ) ) { appendEntries ( member ) ; } }
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 > sendAndReceive ( request ) . whenComplete ( ( response , error ) -> { context . checkThread ( ) ; member . completeConfigure ( ) ; if ( open ) { if ( error == null ) { logger . trace ( "{} - Received {} from {}" , context . getCluster ( ) . member ( ) . address ( ) , response , member . getMember ( ) . serverAddress ( ) ) ; handleConfigureResponse ( member , request , response ) ; } else { logger . warn ( "{} - Failed to configure {}" , context . getCluster ( ) . member ( ) . address ( ) , member . getMember ( ) . serverAddress ( ) ) ; handleConfigureResponseFailure ( member , request , error ) ; } } } ) ; }
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 > sendAndReceive ( request ) . whenComplete ( ( response , error ) -> { context . checkThread ( ) ; member . completeInstall ( ) ; if ( open ) { if ( error == null ) { logger . trace ( "{} - Received {} from {}" , context . getCluster ( ) . member ( ) . address ( ) , response , member . getMember ( ) . serverAddress ( ) ) ; handleInstallResponse ( member , request , response ) ; } else { logger . warn ( "{} - Failed to install {}" , context . getCluster ( ) . member ( ) . address ( ) , member . getMember ( ) . serverAddress ( ) ) ; handleInstallResponseFailure ( member , request , error ) ; } } } ) ; }
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 ) ; } } ; changeListeners . add ( listener ) ; return listener ; }
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 type: " + operation . getClass ( ) ) ; } }
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 IllegalStateException ( "log closed" ) ) ) ; return ; } if ( ! session . state ( ) . active ( ) ) { context . executor ( ) . execute ( ( ) -> future . completeExceptionally ( new UnknownSessionException ( "inactive session: " + session . id ( ) ) ) ) ; return ; } executor . tick ( index , timestamp ) ; executor . init ( index , Instant . ofEpochMilli ( timestamp ) , ServerStateMachineContext . Type . COMMAND ) ; session . clearResults ( commandSequence ) . resendEvents ( eventIndex ) ; long lastCompleted = calculateLastCompleted ( index ) ; executor . commit ( ) ; context . executor ( ) . execute ( ( ) -> { setLastCompleted ( lastCompleted ) ; future . complete ( null ) ; } ) ; }
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 = session . getResult ( sequence ) ; if ( result == null ) { LOGGER . debug ( "Missing command result for {}:{}" , session . id ( ) , sequence ) ; } context . executor ( ) . execute ( ( ) -> future . complete ( 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 IllegalStateException ( "log closed" ) ) ) ; return ; } if ( ! session . state ( ) . active ( ) ) { context . executor ( ) . execute ( ( ) -> future . completeExceptionally ( new UnknownSessionException ( "inactive session: " + session . id ( ) ) ) ) ; return ; } executor . tick ( index , timestamp ) ; executor . init ( commit . index ( ) , commit . time ( ) , ServerStateMachineContext . Type . COMMAND ) ; long eventIndex = session . getEventIndex ( ) ; try { Object output = executor . executeOperation ( commit ) ; executor . commit ( ) ; Result result = new Result ( index , eventIndex , output ) ; session . registerResult ( sequence , result ) ; context . executor ( ) . execute ( ( ) -> future . complete ( result ) ) ; } catch ( Exception e ) { Result result = new Result ( index , eventIndex , e ) ; session . registerResult ( sequence , result ) ; context . executor ( ) . execute ( ( ) -> future . complete ( result ) ) ; } }
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 ( ! session . state ( ) . active ( ) ) { context . executor ( ) . execute ( ( ) -> future . completeExceptionally ( new UnknownSessionException ( "inactive session: " + session . id ( ) ) ) ) ; return ; } long index = commit . index ( ) ; long eventIndex = session . getEventIndex ( ) ; executor . init ( index , commit . time ( ) , ServerStateMachineContext . Type . QUERY ) ; try { Object result = executor . executeOperation ( commit ) ; context . executor ( ) . execute ( ( ) -> future . complete ( new Result ( index , eventIndex , result ) ) ) ; } catch ( Exception e ) { context . executor ( ) . execute ( ( ) -> future . complete ( new Result ( index , eventIndex , e ) ) ) ; } }
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 : return queryBoundedLinearizable ( entry ) ; case LINEARIZABLE : return queryLinearizable ( entry ) ; default : throw new IllegalStateException ( "unknown consistency level" ) ; } }
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 ( QueryResponse . builder ( ) . withStatus ( Response . Status . ERROR ) . withError ( CopycatError . Type . UNKNOWN_SESSION_ERROR ) . build ( ) ) ) ; } CompletableFuture < QueryResponse > future = new CompletableFuture < > ( ) ; if ( entry . getSequence ( ) > session . getCommandSequence ( ) ) { session . registerSequenceQuery ( entry . getSequence ( ) , ( ) -> applyQuery ( entry , future ) ) ; } else { applyQuery ( entry , future ) ; } return future ; }
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 .