idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
19,900
private synchronized void recomputeTerm ( PartitionGroupMembership membership ) { if ( membership == null ) { return ; } List < GroupMember > candidates = new ArrayList < > ( ) ; for ( MemberId memberId : membership . members ( ) ) { Member member = clusterMembershipService . getMember ( memberId ) ; if ( member != null && member . isReachable ( ) ) { candidates . add ( new GroupMember ( memberId , MemberGroupId . from ( memberId . id ( ) ) ) ) ; } } candidates . sort ( ( a , b ) -> { int aoffset = Hashing . murmur3_32 ( ) . hashString ( a . memberId ( ) . id ( ) , StandardCharsets . UTF_8 ) . asInt ( ) % partitionId . id ( ) ; int boffset = Hashing . murmur3_32 ( ) . hashString ( b . memberId ( ) . id ( ) , StandardCharsets . UTF_8 ) . asInt ( ) % partitionId . id ( ) ; return aoffset - boffset ; } ) ; PrimaryTerm currentTerm = this . currentTerm ; GroupMember primary = candidates . isEmpty ( ) ? null : candidates . get ( 0 ) ; candidates = candidates . isEmpty ( ) ? Collections . emptyList ( ) : candidates . subList ( 1 , candidates . size ( ) ) ; long term = currentTerm != null && Objects . equals ( currentTerm . primary ( ) , primary ) && Objects . equals ( currentTerm . candidates ( ) , candidates ) ? currentTerm ( ) : incrementTerm ( ) ; PrimaryTerm newTerm = new PrimaryTerm ( term , primary , candidates ) ; if ( ! Objects . equals ( currentTerm , newTerm ) ) { this . currentTerm = newTerm ; LOGGER . debug ( "{} - Recomputed term for partition {}: {}" , clusterMembershipService . getLocalMember ( ) . id ( ) , partitionId , newTerm ) ; post ( new PrimaryElectionEvent ( PrimaryElectionEvent . Type . CHANGED , partitionId , newTerm ) ) ; broadcastCounters ( ) ; } }
Recomputes the current term .
19,901
void close ( ) { broadcastFuture . cancel ( false ) ; groupMembershipService . removeListener ( groupMembershipEventListener ) ; clusterMembershipService . removeListener ( clusterMembershipEventListener ) ; }
Closes the election .
19,902
public LogicalTimestamp update ( LogicalTimestamp timestamp ) { if ( timestamp . value ( ) > currentTimestamp . value ( ) ) { this . currentTimestamp = timestamp ; } return currentTimestamp ; }
Updates the clock using the given timestamp .
19,903
public LogicalTimestamp incrementAndUpdate ( LogicalTimestamp timestamp ) { long nextValue = currentTimestamp . value ( ) + 1 ; if ( timestamp . value ( ) > nextValue ) { return update ( timestamp ) ; } return increment ( ) ; }
Increments the clock and updates it using the given timestamp .
19,904
protected CompletableFuture < AppendResponse > handleAppend ( final AppendRequest request ) { CompletableFuture < AppendResponse > future = new CompletableFuture < > ( ) ; if ( ! checkTerm ( request , future ) ) { return future ; } if ( ! checkPreviousEntry ( request , future ) ) { return future ; } appendEntries ( request , future ) ; return future ; }
Handles an AppendRequest .
19,905
protected boolean checkTerm ( AppendRequest request , CompletableFuture < AppendResponse > future ) { RaftLogWriter writer = raft . getLogWriter ( ) ; if ( request . term ( ) < raft . getTerm ( ) ) { log . debug ( "Rejected {}: request term is less than the current term ({})" , request , raft . getTerm ( ) ) ; return failAppend ( writer . getLastIndex ( ) , future ) ; } return true ; }
Checks the leader s term of the given AppendRequest returning a boolean indicating whether to continue handling the request .
19,906
protected boolean checkPreviousEntry ( AppendRequest request , CompletableFuture < AppendResponse > future ) { RaftLogWriter writer = raft . getLogWriter ( ) ; RaftLogReader reader = raft . getLogReader ( ) ; if ( request . prevLogTerm ( ) != 0 ) { Indexed < RaftLogEntry > lastEntry = writer . getLastEntry ( ) ; if ( lastEntry != null ) { if ( request . prevLogIndex ( ) > lastEntry . index ( ) ) { log . debug ( "Rejected {}: Previous index ({}) is greater than the local log's last index ({})" , request , request . prevLogIndex ( ) , lastEntry . index ( ) ) ; return failAppend ( lastEntry . index ( ) , future ) ; } if ( request . prevLogIndex ( ) < lastEntry . index ( ) ) { if ( reader . getNextIndex ( ) != request . prevLogIndex ( ) ) { reader . reset ( request . prevLogIndex ( ) ) ; } if ( ! reader . hasNext ( ) ) { log . debug ( "Rejected {}: Previous entry does not exist in the local log" , request ) ; return failAppend ( lastEntry . index ( ) , future ) ; } Indexed < RaftLogEntry > previousEntry = reader . next ( ) ; if ( request . prevLogTerm ( ) != previousEntry . entry ( ) . term ( ) ) { log . debug ( "Rejected {}: Previous entry term ({}) does not match local log's term for the same entry ({})" , request , request . prevLogTerm ( ) , previousEntry . entry ( ) . term ( ) ) ; return failAppend ( request . prevLogIndex ( ) - 1 , future ) ; } } else if ( request . prevLogTerm ( ) != lastEntry . entry ( ) . term ( ) ) { log . debug ( "Rejected {}: Previous entry term ({}) does not equal the local log's last term ({})" , request , request . prevLogTerm ( ) , lastEntry . entry ( ) . term ( ) ) ; return failAppend ( request . prevLogIndex ( ) - 1 , future ) ; } } else { if ( request . prevLogIndex ( ) > 0 ) { log . debug ( "Rejected {}: Previous index ({}) is greater than the local log's last index (0)" , request , request . prevLogIndex ( ) ) ; return failAppend ( 0 , future ) ; } } } return true ; }
Checks the previous index of the given AppendRequest returning a boolean indicating whether to continue handling the request .
19,907
protected boolean completeAppend ( boolean succeeded , long lastLogIndex , CompletableFuture < AppendResponse > future ) { future . complete ( logResponse ( AppendResponse . builder ( ) . withStatus ( RaftResponse . Status . OK ) . withTerm ( raft . getTerm ( ) ) . withSucceeded ( succeeded ) . withLastLogIndex ( lastLogIndex ) . build ( ) ) ) ; return succeeded ; }
Returns a successful append response .
19,908
private void applyOperations ( long fromIndex , long toIndex ) { for ( long i = fromIndex + 1 ; i <= toIndex ; i ++ ) { BackupOperation operation = operations . poll ( ) ; if ( operation == null ) { requestRestore ( context . primary ( ) ) ; break ; } if ( context . nextIndex ( operation . index ( ) ) ) { switch ( operation . type ( ) ) { case EXECUTE : applyExecute ( ( ExecuteOperation ) operation ) ; break ; case HEARTBEAT : applyHeartbeat ( ( HeartbeatOperation ) operation ) ; break ; case EXPIRE : applyExpire ( ( ExpireOperation ) operation ) ; break ; case CLOSE : applyClose ( ( CloseOperation ) operation ) ; break ; } } else if ( operation . index ( ) < i ) { continue ; } else { requestRestore ( context . primary ( ) ) ; break ; } } }
Applies operations in the given range .
19,909
private void applyExecute ( ExecuteOperation operation ) { Session session = context . getOrCreateSession ( operation . session ( ) , operation . node ( ) ) ; if ( operation . operation ( ) != null ) { try { context . service ( ) . apply ( new DefaultCommit < > ( context . setIndex ( operation . index ( ) ) , operation . operation ( ) . id ( ) , operation . operation ( ) . value ( ) , context . setSession ( session ) , context . setTimestamp ( operation . timestamp ( ) ) ) ) ; } catch ( Exception e ) { log . warn ( "Failed to apply operation: {}" , e ) ; } finally { context . setSession ( null ) ; } } }
Applies an execute operation to the service .
19,910
private void applyExpire ( ExpireOperation operation ) { context . setTimestamp ( operation . timestamp ( ) ) ; PrimaryBackupSession session = context . getSession ( operation . session ( ) ) ; if ( session != null ) { context . expireSession ( session . sessionId ( ) . id ( ) ) ; } }
Applies an expire operation .
19,911
private void applyClose ( CloseOperation operation ) { context . setTimestamp ( operation . timestamp ( ) ) ; PrimaryBackupSession session = context . getSession ( operation . session ( ) ) ; if ( session != null ) { context . closeSession ( session . sessionId ( ) . id ( ) ) ; } }
Applies a close operation .
19,912
private void requestRestore ( MemberId primary ) { context . protocol ( ) . restore ( primary , RestoreRequest . request ( context . descriptor ( ) , context . currentTerm ( ) ) ) . whenCompleteAsync ( ( response , error ) -> { if ( error == null && response . status ( ) == PrimaryBackupResponse . Status . OK ) { context . resetIndex ( response . index ( ) , response . timestamp ( ) ) ; Buffer buffer = HeapBuffer . wrap ( response . data ( ) ) ; int sessions = buffer . readInt ( ) ; for ( int i = 0 ; i < sessions ; i ++ ) { context . getOrCreateSession ( buffer . readLong ( ) , MemberId . from ( buffer . readString ( ) ) ) ; } context . service ( ) . restore ( new DefaultBackupInput ( buffer , context . service ( ) . serializer ( ) ) ) ; operations . clear ( ) ; } } , context . threadContext ( ) ) ; }
Requests a restore from the primary .
19,913
private String getEventLogName ( String subject , String id ) { return String . format ( "%s-%s" , subject , id ) ; }
Returns an event log name .
19,914
private Session getOrCreateSession ( SessionId sessionId ) { Session session = sessions . get ( sessionId ) ; if ( session == null ) { session = new LocalSession ( sessionId , name ( ) , type ( ) , null , service . serializer ( ) ) ; sessions . put ( session . sessionId ( ) , session ) ; service . register ( session ) ; } return session ; }
Gets or creates a session .
19,915
@ SuppressWarnings ( "unchecked" ) private void consume ( LogRecord record ) { LogOperation operation = decodeInternal ( record . value ( ) ) ; if ( ! operation . primitive ( ) . equals ( name ( ) ) ) { return ; } Session session = getOrCreateSession ( operation . sessionId ( ) ) ; currentIndex = record . index ( ) ; currentSession = session ; currentOperation = operation . operationId ( ) . type ( ) ; currentTimestamp = record . timestamp ( ) ; byte [ ] output = service . apply ( new DefaultCommit < > ( currentIndex , operation . operationId ( ) , operation . operation ( ) , currentSession , currentTimestamp ) ) ; if ( operation . sessionId ( ) . equals ( this . session . sessionId ( ) ) ) { CompletableFuture future = writeFutures . remove ( operation . operationIndex ( ) ) ; if ( future != null ) { future . complete ( decode ( output ) ) ; } } PendingRead pendingRead = pendingReads . peek ( ) ; while ( pendingRead != null && pendingRead . index <= record . index ( ) ) { session = getOrCreateSession ( this . session . sessionId ( ) ) ; currentSession = session ; currentOperation = OperationType . QUERY ; try { output = service . apply ( new DefaultCommit < > ( currentIndex , pendingRead . operationId , pendingRead . bytes , session , currentTimestamp ) ) ; pendingRead . future . complete ( output ) ; } catch ( Exception e ) { pendingRead . future . completeExceptionally ( new PrimitiveException . ServiceException ( ) ) ; } pendingReads . remove ( ) ; pendingRead = pendingReads . peek ( ) ; } }
Consumes a record from the log .
19,916
protected boolean valuesEqual ( MapEntryValue oldValue , MapEntryValue newValue ) { return ( oldValue == null && newValue == null ) || ( oldValue != null && newValue != null && valuesEqual ( oldValue . value ( ) , newValue . value ( ) ) ) ; }
Returns a boolean indicating whether the given MapEntryValues are equal .
19,917
protected boolean valuesEqual ( byte [ ] oldValue , byte [ ] newValue ) { return ( oldValue == null && newValue == null ) || ( oldValue != null && newValue != null && Arrays . equals ( oldValue , newValue ) ) ; }
Returns a boolean indicating whether the given entry values are equal .
19,918
protected boolean valueIsNull ( MapEntryValue value ) { return value == null || value . type ( ) == MapEntryValue . Type . TOMBSTONE ; }
Returns a boolean indicating whether the given MapEntryValue is null or a tombstone .
19,919
protected void putValue ( K key , MapEntryValue value ) { MapEntryValue oldValue = entries ( ) . put ( key , value ) ; cancelTtl ( oldValue ) ; scheduleTtl ( key , value ) ; }
Updates the given value .
19,920
protected void scheduleTtl ( K key , MapEntryValue value ) { if ( value . ttl ( ) > 0 ) { value . timer = getScheduler ( ) . schedule ( Duration . ofMillis ( value . ttl ( ) ) , ( ) -> { entries ( ) . remove ( key , value ) ; publish ( new AtomicMapEvent < > ( AtomicMapEvent . Type . REMOVE , key , null , toVersioned ( value ) ) ) ; } ) ; } }
Schedules the TTL for the given value .
19,921
protected void cancelTtl ( MapEntryValue value ) { if ( value != null && value . timer != null ) { value . timer . cancel ( ) ; } }
Cancels the TTL for the given value .
19,922
private MapEntryUpdateResult < K , byte [ ] > removeIf ( long index , K key , Predicate < MapEntryValue > predicate ) { MapEntryValue value = entries ( ) . get ( key ) ; if ( valueIsNull ( value ) || ! predicate . test ( value ) ) { return new MapEntryUpdateResult < > ( MapEntryUpdateResult . Status . PRECONDITION_FAILED , index , key , null ) ; } if ( preparedKeys . contains ( key ) ) { return new MapEntryUpdateResult < > ( MapEntryUpdateResult . Status . WRITE_LOCK , index , key , null ) ; } if ( activeTransactions . isEmpty ( ) ) { entries ( ) . remove ( key ) ; } else { entries ( ) . put ( key , new MapEntryValue ( MapEntryValue . Type . TOMBSTONE , index , null , 0 , 0 ) ) ; } cancelTtl ( value ) ; Versioned < byte [ ] > result = toVersioned ( value ) ; publish ( new AtomicMapEvent < > ( AtomicMapEvent . Type . REMOVE , key , null , result ) ) ; return new MapEntryUpdateResult < > ( MapEntryUpdateResult . Status . OK , index , key , result ) ; }
Handles a remove commit .
19,923
private MapEntryUpdateResult < K , byte [ ] > replaceIf ( long index , K key , MapEntryValue newValue , Predicate < MapEntryValue > predicate ) { MapEntryValue oldValue = entries ( ) . get ( key ) ; if ( valueIsNull ( oldValue ) || ! predicate . test ( oldValue ) ) { return new MapEntryUpdateResult < > ( MapEntryUpdateResult . Status . PRECONDITION_FAILED , index , key , toVersioned ( oldValue ) ) ; } if ( preparedKeys . contains ( key ) ) { return new MapEntryUpdateResult < > ( MapEntryUpdateResult . Status . WRITE_LOCK , index , key , null ) ; } putValue ( key , newValue ) ; Versioned < byte [ ] > result = toVersioned ( oldValue ) ; publish ( new AtomicMapEvent < > ( AtomicMapEvent . Type . UPDATE , key , toVersioned ( newValue ) , result ) ) ; return new MapEntryUpdateResult < > ( MapEntryUpdateResult . Status . OK , index , key , result ) ; }
Handles a replace commit .
19,924
private CommitResult commitTransaction ( TransactionScope < K > transactionScope ) { TransactionLog < MapUpdate < K , byte [ ] > > transactionLog = transactionScope . transactionLog ( ) ; boolean retainTombstones = ! activeTransactions . isEmpty ( ) ; List < AtomicMapEvent < K , byte [ ] > > eventsToPublish = Lists . newArrayList ( ) ; for ( MapUpdate < K , byte [ ] > record : transactionLog . records ( ) ) { if ( record . type ( ) == MapUpdate . Type . VERSION_MATCH ) { continue ; } K key = record . key ( ) ; checkState ( preparedKeys . remove ( key ) , "key is not prepared" ) ; if ( record . type ( ) == MapUpdate . Type . LOCK ) { continue ; } MapEntryValue previousValue = entries ( ) . remove ( key ) ; cancelTtl ( previousValue ) ; MapEntryValue newValue = null ; if ( record . type ( ) != MapUpdate . Type . REMOVE_IF_VERSION_MATCH ) { newValue = new MapEntryValue ( MapEntryValue . Type . VALUE , currentVersion , record . value ( ) , 0 , 0 ) ; } else if ( retainTombstones ) { newValue = new MapEntryValue ( MapEntryValue . Type . TOMBSTONE , currentVersion , null , 0 , 0 ) ; } AtomicMapEvent < K , byte [ ] > event ; if ( newValue != null ) { entries ( ) . put ( key , newValue ) ; if ( ! valueIsNull ( newValue ) ) { if ( ! valueIsNull ( previousValue ) ) { event = new AtomicMapEvent < > ( AtomicMapEvent . Type . UPDATE , key , toVersioned ( newValue ) , toVersioned ( previousValue ) ) ; } else { event = new AtomicMapEvent < > ( AtomicMapEvent . Type . INSERT , key , toVersioned ( newValue ) , null ) ; } } else { event = new AtomicMapEvent < > ( AtomicMapEvent . Type . REMOVE , key , null , toVersioned ( previousValue ) ) ; } } else { event = new AtomicMapEvent < > ( AtomicMapEvent . Type . REMOVE , key , null , toVersioned ( previousValue ) ) ; } eventsToPublish . add ( event ) ; } publish ( eventsToPublish ) ; return CommitResult . OK ; }
Applies committed operations to the state machine .
19,925
private void discardTombstones ( ) { if ( activeTransactions . isEmpty ( ) ) { Iterator < Map . Entry < K , MapEntryValue > > iterator = entries ( ) . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { MapEntryValue value = iterator . next ( ) . getValue ( ) ; if ( value . type ( ) == MapEntryValue . Type . TOMBSTONE ) { iterator . remove ( ) ; } } } else { long lowWaterMark = activeTransactions . values ( ) . stream ( ) . mapToLong ( TransactionScope :: version ) . min ( ) . getAsLong ( ) ; Iterator < Map . Entry < K , MapEntryValue > > iterator = entries ( ) . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { MapEntryValue value = iterator . next ( ) . getValue ( ) ; if ( value . type ( ) == MapEntryValue . Type . TOMBSTONE && value . version < lowWaterMark ) { iterator . remove ( ) ; } } } }
Discards tombstones no longer needed by active transactions .
19,926
private void publish ( List < AtomicMapEvent < K , byte [ ] > > events ) { listeners . forEach ( listener -> events . forEach ( event -> getSession ( listener ) . accept ( client -> client . change ( event ) ) ) ) ; }
Publishes events to listeners .
19,927
protected PrimitiveProtocol protocol ( ) { PrimitiveProtocol protocol = this . protocol ; if ( protocol == null ) { PrimitiveProtocolConfig < ? > protocolConfig = config . getProtocolConfig ( ) ; if ( protocolConfig == null ) { Collection < PartitionGroup > partitionGroups = managementService . getPartitionService ( ) . getPartitionGroups ( ) ; if ( partitionGroups . size ( ) == 1 ) { protocol = partitionGroups . iterator ( ) . next ( ) . newProtocol ( ) ; } else { String groups = Joiner . on ( ", " ) . join ( partitionGroups . stream ( ) . map ( group -> group . name ( ) ) . collect ( Collectors . toList ( ) ) ) ; throw new ConfigurationException ( String . format ( "Primitive protocol is ambiguous: %d partition groups found (%s)" , partitionGroups . size ( ) , groups ) ) ; } } else { protocol = protocolConfig . getType ( ) . newProtocol ( protocolConfig ) ; } } return protocol ; }
Returns the primitive protocol .
19,928
public static < V > DocumentTreeResult < V > ok ( V result ) { return new DocumentTreeResult < V > ( Status . OK , result ) ; }
Returns a successful result .
19,929
public static PrimitiveEvent event ( EventType eventType , byte [ ] value ) { return new PrimitiveEvent ( EventType . canonical ( eventType ) , value ) ; }
Creates a new primitive event .
19,930
public static < T > CollectionUpdateResult < T > ok ( T result ) { return new CollectionUpdateResult < > ( Status . OK , result ) ; }
Returns a successful update result .
19,931
public static < T > CollectionUpdateResult < T > noop ( T result ) { return new CollectionUpdateResult < > ( Status . NOOP , result ) ; }
Returns a no - op result .
19,932
public static PrimitiveOperation operation ( OperationId id , byte [ ] value ) { return new PrimitiveOperation ( OperationId . simplify ( id ) , value ) ; }
Creates a new primitive operation with a simplified identifier .
19,933
public static Version from ( String version ) { String [ ] fields = version . split ( "[.-]" , 4 ) ; checkArgument ( fields . length >= 3 , "version number is invalid" ) ; return new Version ( parseInt ( fields [ 0 ] ) , parseInt ( fields [ 1 ] ) , parseInt ( fields [ 2 ] ) , fields . length == 4 ? fields [ 3 ] : null ) ; }
Returns a new version from the given version string .
19,934
public static Version from ( int major , int minor , int patch , String build ) { return new Version ( major , minor , patch , build ) ; }
Returns a new version from the given parts .
19,935
public < T > T loadFiles ( Class < T > type , List < File > files , List < String > resources ) { if ( files == null ) { return loadResources ( type , resources ) ; } Config config = ConfigFactory . systemProperties ( ) ; for ( File file : files ) { config = config . withFallback ( ConfigFactory . parseFile ( file , ConfigParseOptions . defaults ( ) . setAllowMissing ( false ) ) ) ; } for ( String resource : resources ) { config = config . withFallback ( ConfigFactory . load ( classLoader , resource ) ) ; } return map ( checkNotNull ( config , "config cannot be null" ) . resolve ( ) , type ) ; }
Loads the given configuration file using the mapper falling back to the given resources .
19,936
@ SuppressWarnings ( "unchecked" ) private static < T > T newInstance ( Class < ? > type ) { try { return ( T ) type . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new ServiceException ( "Cannot instantiate service class " + type , e ) ; } }
Instantiates the given type using a no - argument constructor .
19,937
public static void main ( String [ ] args ) throws Exception { final List < String > unknown = new ArrayList < > ( ) ; final Namespace namespace = parseArgs ( args , unknown ) ; final Namespace extraArgs = parseUnknown ( unknown ) ; extraArgs . getAttrs ( ) . forEach ( ( key , value ) -> System . setProperty ( key , value . toString ( ) ) ) ; final Logger logger = createLogger ( namespace ) ; final Atomix atomix = buildAtomix ( namespace ) ; atomix . start ( ) . join ( ) ; logger . info ( "Atomix listening at {}" , atomix . getMembershipService ( ) . getLocalMember ( ) . address ( ) ) ; final ManagedRestService rest = buildRestService ( atomix , namespace ) ; rest . start ( ) . join ( ) ; logger . warn ( "The Atomix HTTP API is BETA and is intended for development and debugging purposes only!" ) ; logger . info ( "HTTP server listening at {}" , rest . address ( ) ) ; synchronized ( Atomix . class ) { while ( atomix . isRunning ( ) ) { Atomix . class . wait ( ) ; } } }
Runs a standalone Atomix agent from the given command line arguments .
19,938
static Namespace parseArgs ( String [ ] args , List < String > unknown ) { ArgumentParser parser = createParser ( ) ; Namespace namespace = null ; try { namespace = parser . parseKnownArgs ( args , unknown ) ; } catch ( ArgumentParserException e ) { parser . handleError ( e ) ; System . exit ( 1 ) ; } return namespace ; }
Parses the command line arguments returning an argparse4j namespace .
19,939
static Namespace parseUnknown ( List < String > unknown ) { Map < String , Object > attrs = new HashMap < > ( ) ; String attr = null ; for ( String arg : unknown ) { if ( arg . startsWith ( "--" ) ) { int splitIndex = arg . indexOf ( '=' ) ; if ( splitIndex == - 1 ) { attr = arg . substring ( 2 ) ; } else { attrs . put ( arg . substring ( 2 , splitIndex ) , arg . substring ( splitIndex + 1 ) ) ; attr = null ; } } else if ( attr != null ) { attrs . put ( attr , arg ) ; attr = null ; } } return new Namespace ( attrs ) ; }
Parses unknown arguments returning an argparse4j namespace .
19,940
static Logger createLogger ( Namespace namespace ) { String logConfig = namespace . getString ( "log_config" ) ; if ( logConfig != null ) { System . setProperty ( "logback.configurationFile" , logConfig ) ; } System . setProperty ( "atomix.log.directory" , namespace . getString ( "log_dir" ) ) ; System . setProperty ( "atomix.log.level" , namespace . getString ( "log_level" ) ) ; System . setProperty ( "atomix.log.console.level" , namespace . getString ( "console_log_level" ) ) ; System . setProperty ( "atomix.log.file.level" , namespace . getString ( "file_log_level" ) ) ; return LoggerFactory . getLogger ( AtomixAgent . class ) ; }
Configures and creates a new logger for the given namespace .
19,941
static AtomixConfig createConfig ( Namespace namespace ) { final List < File > configFiles = namespace . getList ( "config" ) ; final String memberId = namespace . getString ( "member" ) ; final Address address = namespace . get ( "address" ) ; final String host = namespace . getString ( "host" ) ; final String rack = namespace . getString ( "rack" ) ; final String zone = namespace . getString ( "zone" ) ; final List < NodeConfig > bootstrap = namespace . getList ( "bootstrap" ) ; final boolean multicastEnabled = namespace . getBoolean ( "multicast" ) ; final String multicastGroup = namespace . get ( "multicast_group" ) ; final Integer multicastPort = namespace . get ( "multicast_port" ) ; System . setProperty ( "atomix.data" , namespace . getString ( "data_dir" ) ) ; AtomixConfig config ; if ( configFiles != null && ! configFiles . isEmpty ( ) ) { System . setProperty ( "atomix.config.resources" , "" ) ; config = Atomix . config ( configFiles ) ; } else { config = Atomix . config ( ) ; } if ( memberId != null ) { config . getClusterConfig ( ) . getNodeConfig ( ) . setId ( memberId ) ; } if ( address != null ) { config . getClusterConfig ( ) . getNodeConfig ( ) . setAddress ( address ) ; } if ( host != null ) { config . getClusterConfig ( ) . getNodeConfig ( ) . setHostId ( host ) ; } if ( rack != null ) { config . getClusterConfig ( ) . getNodeConfig ( ) . setRackId ( rack ) ; } if ( zone != null ) { config . getClusterConfig ( ) . getNodeConfig ( ) . setZoneId ( zone ) ; } if ( bootstrap != null && ! bootstrap . isEmpty ( ) ) { config . getClusterConfig ( ) . setDiscoveryConfig ( new BootstrapDiscoveryConfig ( ) . setNodes ( bootstrap ) ) ; } if ( multicastEnabled ) { config . getClusterConfig ( ) . getMulticastConfig ( ) . setEnabled ( true ) ; if ( multicastGroup != null ) { config . getClusterConfig ( ) . getMulticastConfig ( ) . setGroup ( multicastGroup ) ; } if ( multicastPort != null ) { config . getClusterConfig ( ) . getMulticastConfig ( ) . setPort ( multicastPort ) ; } if ( bootstrap == null || bootstrap . isEmpty ( ) ) { config . getClusterConfig ( ) . setDiscoveryConfig ( new MulticastDiscoveryConfig ( ) ) ; } } return config ; }
Creates an Atomix configuration from the given namespace .
19,942
private static Atomix buildAtomix ( Namespace namespace ) { return Atomix . builder ( createConfig ( namespace ) ) . withShutdownHookEnabled ( ) . build ( ) ; }
Builds a new Atomix instance from the given namespace .
19,943
private static ManagedRestService buildRestService ( Atomix atomix , Namespace namespace ) { final String httpHost = namespace . getString ( "http_host" ) ; final Integer httpPort = namespace . getInt ( "http_port" ) ; return RestService . builder ( ) . withAtomix ( atomix ) . withAddress ( Address . from ( httpHost , httpPort ) ) . build ( ) ; }
Builds a REST service for the given Atomix instance from the given namespace .
19,944
public static Address from ( int port ) { try { InetAddress address = getLocalAddress ( ) ; return new Address ( address . getHostName ( ) , port ) ; } catch ( UnknownHostException e ) { throw new IllegalArgumentException ( "Failed to locate host" , e ) ; } }
Returns an address for the local host and the given port .
19,945
private static InetAddress getLocalAddress ( ) throws UnknownHostException { try { return InetAddress . getLocalHost ( ) ; } catch ( Exception ignore ) { return InetAddress . getByName ( null ) ; } }
Returns the local host .
19,946
public InetAddress address ( boolean resolve ) { if ( resolve ) { address = resolveAddress ( ) ; return address ; } if ( address == null ) { synchronized ( this ) { if ( address == null ) { address = resolveAddress ( ) ; } } } return address ; }
Returns the IP address .
19,947
public Type type ( ) { if ( type == null ) { synchronized ( this ) { if ( type == null ) { type = address ( ) instanceof Inet6Address ? Type . IPV6 : Type . IPV4 ; } } } return type ; }
Returns the address type .
19,948
public void installSnapshot ( SnapshotReader reader ) { log . debug ( "Installing snapshot {}" , reader . snapshot ( ) . index ( ) ) ; reader . skip ( Bytes . LONG ) ; PrimitiveType primitiveType ; try { primitiveType = raft . getPrimitiveTypes ( ) . getPrimitiveType ( reader . readString ( ) ) ; } catch ( ConfigurationException e ) { log . error ( e . getMessage ( ) , e ) ; return ; } String serviceName = reader . readString ( ) ; currentIndex = reader . readLong ( ) ; currentTimestamp = reader . readLong ( ) ; timestampDelta = reader . readLong ( ) ; int sessionCount = reader . readInt ( ) ; for ( int i = 0 ; i < sessionCount ; i ++ ) { SessionId sessionId = SessionId . from ( reader . readLong ( ) ) ; MemberId node = MemberId . from ( reader . readString ( ) ) ; ReadConsistency readConsistency = ReadConsistency . valueOf ( reader . readString ( ) ) ; long minTimeout = reader . readLong ( ) ; long maxTimeout = reader . readLong ( ) ; long sessionTimestamp = reader . readLong ( ) ; RaftSession session = raft . getSessions ( ) . addSession ( new RaftSession ( sessionId , node , serviceName , primitiveType , readConsistency , minTimeout , maxTimeout , sessionTimestamp , service . serializer ( ) , this , raft , threadContextFactory ) ) ; session . setRequestSequence ( reader . readLong ( ) ) ; session . setCommandSequence ( reader . readLong ( ) ) ; session . setEventIndex ( reader . readLong ( ) ) ; session . setLastCompleted ( reader . readLong ( ) ) ; session . setLastApplied ( reader . snapshot ( ) . index ( ) ) ; session . setLastUpdated ( sessionTimestamp ) ; session . open ( ) ; service . register ( sessions . addSession ( session ) ) ; } service . restore ( new DefaultBackupInput ( reader , service . serializer ( ) ) ) ; }
Installs a snapshot .
19,949
public void takeSnapshot ( SnapshotWriter writer ) { log . debug ( "Taking snapshot {}" , writer . snapshot ( ) . index ( ) ) ; writer . writeLong ( primitiveId . id ( ) ) ; writer . writeString ( primitiveType . name ( ) ) ; writer . writeString ( serviceName ) ; writer . writeLong ( currentIndex ) ; writer . writeLong ( currentTimestamp ) ; writer . writeLong ( timestampDelta ) ; writer . writeInt ( sessions . getSessions ( ) . size ( ) ) ; for ( RaftSession session : sessions . getSessions ( ) ) { writer . writeLong ( session . sessionId ( ) . id ( ) ) ; writer . writeString ( session . memberId ( ) . id ( ) ) ; writer . writeString ( session . readConsistency ( ) . name ( ) ) ; writer . writeLong ( session . minTimeout ( ) ) ; writer . writeLong ( session . maxTimeout ( ) ) ; writer . writeLong ( session . getLastUpdated ( ) ) ; writer . writeLong ( session . getRequestSequence ( ) ) ; writer . writeLong ( session . getCommandSequence ( ) ) ; writer . writeLong ( session . getEventIndex ( ) ) ; writer . writeLong ( session . getLastCompleted ( ) ) ; } service . backup ( new DefaultBackupOutput ( writer , service . serializer ( ) ) ) ; }
Takes a snapshot of the service state .
19,950
public long openSession ( long index , long timestamp , RaftSession session ) { log . debug ( "Opening session {}" , session . sessionId ( ) ) ; tick ( index , timestamp ) ; session . setLastUpdated ( currentTimestamp ) ; expireSessions ( currentTimestamp ) ; session . open ( ) ; service . register ( sessions . addSession ( session ) ) ; commit ( ) ; return session . sessionId ( ) . id ( ) ; }
Registers the given session .
19,951
public boolean keepAlive ( long index , long timestamp , RaftSession session , long commandSequence , long eventIndex ) { if ( deleted ) { return false ; } tick ( index , timestamp ) ; if ( session . getState ( ) != Session . State . CLOSED ) { session . setLastUpdated ( timestamp ) ; session . clearResults ( commandSequence ) ; session . resendEvents ( eventIndex ) ; session . resetRequestSequence ( commandSequence ) ; session . setCommandSequence ( commandSequence ) ; return true ; } else { return false ; } }
Keeps the given session alive .
19,952
public void keepAliveSessions ( long index , long timestamp ) { log . debug ( "Resetting session timeouts" ) ; this . currentIndex = index ; this . currentTimestamp = Math . max ( currentTimestamp , timestamp ) ; for ( RaftSession session : sessions . getSessions ( primitiveId ) ) { session . setLastUpdated ( timestamp ) ; } }
Keeps all sessions alive using the given timestamp .
19,953
public void closeSession ( long index , long timestamp , RaftSession session , boolean expired ) { log . debug ( "Closing session {}" , session . sessionId ( ) ) ; session . setLastUpdated ( timestamp ) ; tick ( index , timestamp ) ; expireSessions ( currentTimestamp ) ; if ( expired ) { session = sessions . removeSession ( session . sessionId ( ) ) ; if ( session != null ) { session . expire ( ) ; service . expire ( session . sessionId ( ) ) ; } } else { session = sessions . removeSession ( session . sessionId ( ) ) ; if ( session != null ) { session . close ( ) ; service . close ( session . sessionId ( ) ) ; } } commit ( ) ; }
Unregister the given session .
19,954
public OperationResult executeCommand ( long index , long sequence , long timestamp , RaftSession session , PrimitiveOperation operation ) { if ( deleted ) { log . warn ( "Service {} has been deleted by another process" , serviceName ) ; throw new RaftException . UnknownService ( "Service " + serviceName + " has been deleted" ) ; } if ( ! session . getState ( ) . active ( ) ) { log . warn ( "Session not open: {}" , session ) ; throw new RaftException . UnknownSession ( "Unknown session: " + session . sessionId ( ) ) ; } session . setLastUpdated ( timestamp ) ; tick ( index , timestamp ) ; if ( sequence > 0 && sequence < session . nextCommandSequence ( ) ) { log . trace ( "Returning cached result for command with sequence number {} < {}" , sequence , session . nextCommandSequence ( ) ) ; return sequenceCommand ( index , sequence , session ) ; } else { return applyCommand ( index , sequence , timestamp , operation , session ) ; } }
Executes the given command on the state machine .
19,955
private OperationResult sequenceCommand ( long index , long sequence , RaftSession session ) { OperationResult result = session . getResult ( sequence ) ; if ( result == null ) { log . debug ( "Missing command result at index {}" , index ) ; } return result ; }
Loads and returns a cached command result according to the sequence number .
19,956
private OperationResult applyCommand ( long index , long sequence , long timestamp , PrimitiveOperation operation , RaftSession session ) { long eventIndex = session . getEventIndex ( ) ; Commit < byte [ ] > commit = new DefaultCommit < > ( index , operation . id ( ) , operation . value ( ) , session , timestamp ) ; OperationResult result ; try { currentSession = session ; byte [ ] output = service . apply ( commit ) ; result = OperationResult . succeeded ( index , eventIndex , output ) ; } catch ( Exception e ) { result = OperationResult . failed ( index , eventIndex , e ) ; } finally { currentSession = null ; } commit ( ) ; session . registerResult ( sequence , result ) ; session . setCommandSequence ( sequence ) ; return result ; }
Applies the given commit to the state machine .
19,957
public CompletableFuture < OperationResult > executeQuery ( long index , long sequence , long timestamp , RaftSession session , PrimitiveOperation operation ) { CompletableFuture < OperationResult > future = new CompletableFuture < > ( ) ; executeQuery ( index , sequence , timestamp , session , operation , future ) ; return future ; }
Executes the given query on the state machine .
19,958
private void executeQuery ( long index , long sequence , long timestamp , RaftSession session , PrimitiveOperation operation , CompletableFuture < OperationResult > future ) { if ( deleted ) { log . warn ( "Service {} has been deleted by another process" , serviceName ) ; future . completeExceptionally ( new RaftException . UnknownService ( "Service " + serviceName + " has been deleted" ) ) ; return ; } if ( ! session . getState ( ) . active ( ) ) { log . warn ( "Inactive session: " + session . sessionId ( ) ) ; future . completeExceptionally ( new RaftException . UnknownSession ( "Unknown session: " + session . sessionId ( ) ) ) ; return ; } sequenceQuery ( index , sequence , timestamp , session , operation , future ) ; }
Executes a query on the state machine thread .
19,959
public void close ( ) { for ( RaftSession serviceSession : sessions . getSessions ( serviceId ( ) ) ) { serviceSession . close ( ) ; service . close ( serviceSession . sessionId ( ) ) ; } service . close ( ) ; deleted = true ; }
Closes the service context .
19,960
public CompletableFuture < Void > shutdown ( ) { if ( ! started ) { return Futures . exceptionalFuture ( new IllegalStateException ( "Server not running" ) ) ; } CompletableFuture < Void > future = new AtomixFuture < > ( ) ; context . getThreadContext ( ) . execute ( ( ) -> { started = false ; context . transition ( Role . INACTIVE ) ; future . complete ( null ) ; } ) ; return future . whenCompleteAsync ( ( result , error ) -> { context . close ( ) ; started = false ; } ) ; }
Shuts down the server without leaving the Raft cluster .
19,961
public static Type getGenericClassType ( Object instance , Class < ? > clazz , int position ) { Class < ? > type = instance . getClass ( ) ; while ( type != Object . class ) { if ( type . getGenericSuperclass ( ) instanceof ParameterizedType ) { ParameterizedType genericSuperclass = ( ParameterizedType ) type . getGenericSuperclass ( ) ; if ( genericSuperclass . getRawType ( ) == clazz ) { return genericSuperclass . getActualTypeArguments ( ) [ position ] ; } else { type = type . getSuperclass ( ) ; } } else { type = type . getSuperclass ( ) ; } } return null ; }
Returns the generic type at the given position for the given class .
19,962
public static Type getGenericInterfaceType ( Object instance , Class < ? > iface , int position ) { Class < ? > type = instance . getClass ( ) ; while ( type != Object . class ) { for ( Type genericType : type . getGenericInterfaces ( ) ) { if ( genericType instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) genericType ; if ( parameterizedType . getRawType ( ) == iface ) { return parameterizedType . getActualTypeArguments ( ) [ position ] ; } } } type = type . getSuperclass ( ) ; } return null ; }
Returns the generic type at the given position for the given interface .
19,963
private void heartbeat ( ) { long index = context . nextIndex ( ) ; long timestamp = System . currentTimeMillis ( ) ; replicator . replicate ( new HeartbeatOperation ( index , timestamp ) ) . thenRun ( ( ) -> context . setTimestamp ( timestamp ) ) ; }
Applies a heartbeat to the service to ensure timers can be triggered .
19,964
public RaftSession addSession ( RaftSession session ) { RaftSession existingSession = sessions . putIfAbsent ( session . sessionId ( ) . id ( ) , session ) ; return existingSession != null ? existingSession : session ; }
Adds a session .
19,965
public Collection < RaftSession > getSessions ( PrimitiveId primitiveId ) { return sessions . values ( ) . stream ( ) . filter ( session -> session . getService ( ) . serviceId ( ) . equals ( primitiveId ) ) . filter ( session -> session . getState ( ) . active ( ) ) . collect ( Collectors . toSet ( ) ) ; }
Returns a set of sessions associated with the given service .
19,966
public void removeSessions ( PrimitiveId primitiveId ) { sessions . entrySet ( ) . removeIf ( e -> e . getValue ( ) . getService ( ) . serviceId ( ) . equals ( primitiveId ) ) ; }
Removes all sessions registered for the given service .
19,967
SnapshotDescriptor copyTo ( Buffer buffer ) { this . buffer = buffer . writeLong ( index ) . writeLong ( timestamp ) . writeInt ( version ) . writeBoolean ( locked ) . skip ( BYTES - buffer . position ( ) ) . flush ( ) ; return this ; }
Copies the snapshot to a new buffer .
19,968
public void resetConnections ( MemberId leader , Collection < MemberId > servers ) { selectorManager . resetAll ( leader , servers ) ; }
Resets the session manager s cluster information .
19,969
public CompletableFuture < RaftSessionState > openSession ( String serviceName , PrimitiveType primitiveType , ServiceConfig config , ReadConsistency readConsistency , CommunicationStrategy communicationStrategy , Duration minTimeout , Duration maxTimeout ) { checkNotNull ( serviceName , "serviceName cannot be null" ) ; checkNotNull ( primitiveType , "serviceType cannot be null" ) ; checkNotNull ( communicationStrategy , "communicationStrategy cannot be null" ) ; checkNotNull ( maxTimeout , "timeout cannot be null" ) ; log . debug ( "Opening session; name: {}, type: {}" , serviceName , primitiveType ) ; OpenSessionRequest request = OpenSessionRequest . builder ( ) . withMemberId ( memberId ) . withServiceName ( serviceName ) . withServiceType ( primitiveType ) . withServiceConfig ( Serializer . using ( primitiveType . namespace ( ) ) . encode ( config ) ) . withReadConsistency ( readConsistency ) . withMinTimeout ( minTimeout . toMillis ( ) ) . withMaxTimeout ( maxTimeout . toMillis ( ) ) . build ( ) ; CompletableFuture < RaftSessionState > future = new CompletableFuture < > ( ) ; ThreadContext proxyContext = threadContextFactory . createContext ( ) ; connection . openSession ( request ) . whenCompleteAsync ( ( response , error ) -> { if ( error == null ) { if ( response . status ( ) == RaftResponse . Status . OK ) { RaftSessionState state = new RaftSessionState ( clientId , SessionId . from ( response . session ( ) ) , serviceName , primitiveType , response . timeout ( ) ) ; sessions . put ( state . getSessionId ( ) . id ( ) , state ) ; state . addStateChangeListener ( s -> { if ( s == PrimitiveState . EXPIRED || s == PrimitiveState . CLOSED ) { sessions . remove ( state . getSessionId ( ) . id ( ) ) ; } } ) ; keepAliveSessions ( System . currentTimeMillis ( ) , state . getSessionTimeout ( ) ) ; future . complete ( state ) ; } else { future . completeExceptionally ( new RaftException . Unavailable ( response . error ( ) . message ( ) ) ) ; } } else { future . completeExceptionally ( new RaftException . Unavailable ( error . getMessage ( ) ) ) ; } } , proxyContext ) ; return future ; }
Opens a new session .
19,970
public CompletableFuture < Void > closeSession ( SessionId sessionId , boolean delete ) { RaftSessionState state = sessions . get ( sessionId . id ( ) ) ; if ( state == null ) { return Futures . exceptionalFuture ( new RaftException . UnknownSession ( "Unknown session: " + sessionId ) ) ; } log . debug ( "Closing session {}" , sessionId ) ; CloseSessionRequest request = CloseSessionRequest . builder ( ) . withSession ( sessionId . id ( ) ) . withDelete ( delete ) . build ( ) ; CompletableFuture < Void > future = new CompletableFuture < > ( ) ; connection . closeSession ( request ) . whenComplete ( ( response , error ) -> { sessions . remove ( sessionId . id ( ) ) ; if ( error == null ) { if ( response . status ( ) == RaftResponse . Status . OK ) { future . complete ( null ) ; } else { future . completeExceptionally ( response . error ( ) . createException ( ) ) ; } } else { future . completeExceptionally ( error ) ; } } ) ; return future ; }
Closes a session .
19,971
private synchronized void resetAllIndexes ( ) { Collection < RaftSessionState > sessions = Lists . newArrayList ( this . sessions . values ( ) ) ; if ( sessions . isEmpty ( ) ) { return ; } long [ ] sessionIds = new long [ sessions . size ( ) ] ; long [ ] commandResponses = new long [ sessions . size ( ) ] ; long [ ] eventIndexes = new long [ sessions . size ( ) ] ; int i = 0 ; for ( RaftSessionState sessionState : sessions ) { sessionIds [ i ] = sessionState . getSessionId ( ) . id ( ) ; commandResponses [ i ] = sessionState . getCommandResponse ( ) ; eventIndexes [ i ] = sessionState . getEventIndex ( ) ; i ++ ; } log . trace ( "Resetting {} sessions" , sessionIds . length ) ; KeepAliveRequest request = KeepAliveRequest . builder ( ) . withSessionIds ( sessionIds ) . withCommandSequences ( commandResponses ) . withEventIndexes ( eventIndexes ) . build ( ) ; connection . keepAlive ( request ) ; }
Resets indexes for all sessions .
19,972
CompletableFuture < Void > resetIndexes ( SessionId sessionId ) { RaftSessionState sessionState = sessions . get ( sessionId . id ( ) ) ; if ( sessionState == null ) { return Futures . exceptionalFuture ( new IllegalArgumentException ( "Unknown session: " + sessionId ) ) ; } CompletableFuture < Void > future = new CompletableFuture < > ( ) ; KeepAliveRequest request = KeepAliveRequest . builder ( ) . withSessionIds ( new long [ ] { sessionId . id ( ) } ) . withCommandSequences ( new long [ ] { sessionState . getCommandResponse ( ) } ) . withEventIndexes ( new long [ ] { sessionState . getEventIndex ( ) } ) . build ( ) ; connection . keepAlive ( request ) . whenComplete ( ( response , error ) -> { if ( error == null ) { if ( response . status ( ) == RaftResponse . Status . OK ) { future . complete ( null ) ; } else { future . completeExceptionally ( response . error ( ) . createException ( ) ) ; } } else { future . completeExceptionally ( error ) ; } } ) ; return future ; }
Resets indexes for the given session .
19,973
private CompletableFuture < HeartbeatResponse > handleHeartbeat ( HeartbeatRequest request ) { log . trace ( "Received {}" , request ) ; boolean newLeader = ! Objects . equals ( selectorManager . leader ( ) , request . leader ( ) ) ; selectorManager . resetAll ( request . leader ( ) , request . members ( ) ) ; HeartbeatResponse response = HeartbeatResponse . builder ( ) . withStatus ( RaftResponse . Status . OK ) . build ( ) ; if ( newLeader ) { resetAllIndexes ( ) ; } log . trace ( "Sending {}" , response ) ; return CompletableFuture . completedFuture ( response ) ; }
Handles a heartbeat request .
19,974
public String getDirectory ( String groupName ) { return directory != null ? directory : System . getProperty ( "atomix.data" , DATA_PREFIX ) + "/" + groupName ; }
Returns the partition data directory .
19,975
private void completeResponses ( ) { ResponseCallback response = responseCallbacks . get ( responseSequence + 1 ) ; while ( response != null ) { if ( completeResponse ( response . response , response . callback ) ) { responseCallbacks . remove ( ++ responseSequence ) ; response = responseCallbacks . get ( responseSequence + 1 ) ; } else { break ; } } if ( requestSequence == responseSequence ) { EventCallback eventCallback = eventCallbacks . poll ( ) ; while ( eventCallback != null ) { log . trace ( "Completing {}" , eventCallback . request ) ; eventCallback . run ( ) ; eventIndex = eventCallback . request . eventIndex ( ) ; eventCallback = eventCallbacks . poll ( ) ; } } }
Completes all sequenced responses .
19,976
public void update ( VectorTimestamp < T > timestamp ) { VectorTimestamp < T > currentTimestamp = vector . get ( timestamp . identifier ( ) ) ; if ( currentTimestamp == null || currentTimestamp . value ( ) < timestamp . value ( ) ) { vector . put ( timestamp . identifier ( ) , timestamp ) ; } }
Updates the given timestamp .
19,977
public void update ( VectorClock < T > clock ) { for ( VectorTimestamp < T > timestamp : clock . vector . values ( ) ) { update ( timestamp ) ; } }
Updates the vector clock .
19,978
private void addReplyTime ( String type , long replyTime ) { DescriptiveStatistics samples = replySamples . get ( type ) ; if ( samples == null ) { samples = replySamples . computeIfAbsent ( type , t -> new SynchronizedDescriptiveStatistics ( WINDOW_SIZE ) ) ; } samples . addValue ( replyTime ) ; }
Adds a reply time to the history .
19,979
private long getTimeoutMillis ( String type , Duration timeout ) { return timeout != null ? timeout . toMillis ( ) : computeTimeoutMillis ( type ) ; }
Returns the timeout in milliseconds for the given timeout duration
19,980
private long computeTimeoutMillis ( String type ) { DescriptiveStatistics samples = replySamples . get ( type ) ; if ( samples == null || samples . getN ( ) < MIN_SAMPLES ) { return MAX_TIMEOUT_MILLIS ; } return Math . min ( Math . max ( ( int ) samples . getMax ( ) * TIMEOUT_FACTOR , MIN_TIMEOUT_MILLIS ) , MAX_TIMEOUT_MILLIS ) ; }
Computes the timeout for the next request .
19,981
public CompletableFuture < T > except ( Consumer < Throwable > consumer ) { return whenComplete ( ( result , error ) -> { if ( error != null ) { consumer . accept ( error ) ; } } ) ; }
Sets a consumer to be called when the future is failed .
19,982
public CompletableFuture < T > exceptAsync ( Consumer < Throwable > consumer ) { return whenCompleteAsync ( ( result , error ) -> { if ( error != null ) { consumer . accept ( error ) ; } } ) ; }
Sets a consumer to be called asynchronously when the future is failed .
19,983
public static boolean isSnapshotFile ( File file ) { checkNotNull ( file , "file cannot be null" ) ; String fileName = file . getName ( ) ; if ( fileName . lastIndexOf ( EXTENSION_SEPARATOR ) == - 1 ) { return false ; } if ( ! fileName . endsWith ( "." + EXTENSION ) ) { return false ; } String [ ] parts = fileName . substring ( 0 , fileName . lastIndexOf ( EXTENSION_SEPARATOR ) ) . split ( String . valueOf ( PART_SEPARATOR ) ) ; if ( parts . length < 2 ) { return false ; } if ( ! isNumeric ( parts [ parts . length - 1 ] ) ) { return false ; } return true ; }
Returns a boolean value indicating whether the given file appears to be a parsable snapshot file .
19,984
private static boolean isNumeric ( String value ) { for ( char c : value . toCharArray ( ) ) { if ( ! Character . isDigit ( c ) ) { return false ; } } return true ; }
Returns a boolean indicating whether the given string value is numeric .
19,985
static String createSnapshotFileName ( String serverName , long index ) { return String . format ( "%s-%d.%s" , serverName , index , EXTENSION ) ; }
Creates a snapshot file name from the given parameters .
19,986
MappedByteBuffer map ( ) { if ( writer instanceof MappedJournalSegmentWriter ) { return ( ( MappedJournalSegmentWriter < E > ) writer ) . buffer ( ) ; } try { JournalWriter < E > writer = this . writer ; MappedByteBuffer buffer = channel . map ( FileChannel . MapMode . READ_WRITE , 0 , segment . descriptor ( ) . maxSegmentSize ( ) ) ; this . writer = new MappedJournalSegmentWriter < > ( buffer , segment , maxEntrySize , index , namespace ) ; writer . close ( ) ; return buffer ; } catch ( IOException e ) { throw new StorageException ( e ) ; } }
Maps the segment writer into memory returning the mapped buffer .
19,987
void unmap ( ) { if ( writer instanceof MappedJournalSegmentWriter ) { JournalWriter < E > writer = this . writer ; this . writer = new FileChannelJournalSegmentWriter < > ( channel , segment , maxEntrySize , index , namespace ) ; writer . close ( ) ; } }
Unmaps the mapped buffer .
19,988
public SwimMembershipProtocolConfig setProbeInterval ( Duration probeInterval ) { checkNotNull ( probeInterval , "probeInterval cannot be null" ) ; checkArgument ( ! probeInterval . isNegative ( ) && ! probeInterval . isZero ( ) , "probeInterval must be positive" ) ; this . probeInterval = probeInterval ; return this ; }
Sets the probe interval .
19,989
public SwimMembershipProtocolConfig setProbeTimeout ( Duration probeTimeout ) { checkNotNull ( probeTimeout , "probeTimeout cannot be null" ) ; checkArgument ( ! probeTimeout . isNegative ( ) && ! probeTimeout . isZero ( ) , "probeTimeout must be positive" ) ; this . probeTimeout = probeTimeout ; return this ; }
Sets the probe timeout .
19,990
public SwimMembershipProtocolConfig setFailureTimeout ( Duration failureTimeout ) { checkNotNull ( failureTimeout , "failureTimeout cannot be null" ) ; checkArgument ( ! failureTimeout . isNegative ( ) && ! failureTimeout . isZero ( ) , "failureTimeout must be positive" ) ; this . failureTimeout = checkNotNull ( failureTimeout ) ; return this ; }
Sets the base failure timeout .
19,991
String publishSubject ( long sessionId ) { if ( prefix == null ) { return String . format ( "publish-%d" , sessionId ) ; } else { return String . format ( "%s-publish-%d" , prefix , sessionId ) ; } }
Returns the publish subject for the given session .
19,992
String resetSubject ( long sessionId ) { if ( prefix == null ) { return String . format ( "reset-%d" , sessionId ) ; } else { return String . format ( "%s-reset-%d" , prefix , sessionId ) ; } }
Returns the reset subject for the given session .
19,993
public SegmentedJournalReader < E > openReader ( long index , SegmentedJournalReader . Mode mode ) { SegmentedJournalReader < E > reader = new SegmentedJournalReader < > ( this , index , mode ) ; readers . add ( reader ) ; return reader ; }
Opens a new Raft log reader with the given reader mode .
19,994
JournalSegment < E > resetSegments ( long index ) { assertOpen ( ) ; JournalSegment < E > firstSegment = getFirstSegment ( ) ; if ( index == firstSegment . index ( ) ) { return firstSegment ; } for ( JournalSegment < E > segment : segments . values ( ) ) { segment . close ( ) ; segment . delete ( ) ; } segments . clear ( ) ; JournalSegmentDescriptor descriptor = JournalSegmentDescriptor . builder ( ) . withId ( 1 ) . withIndex ( index ) . withMaxSegmentSize ( maxSegmentSize ) . withMaxEntries ( maxEntriesPerSegment ) . build ( ) ; currentSegment = createSegment ( descriptor ) ; segments . put ( index , currentSegment ) ; return currentSegment ; }
Resets and returns the first segment in the journal .
19,995
JournalSegment < E > getNextSegment ( long index ) { Map . Entry < Long , JournalSegment < E > > nextSegment = segments . higherEntry ( index ) ; return nextSegment != null ? nextSegment . getValue ( ) : null ; }
Returns the segment following the segment with the given ID .
19,996
synchronized void removeSegment ( JournalSegment segment ) { segments . remove ( segment . index ( ) ) ; segment . close ( ) ; segment . delete ( ) ; resetCurrentSegment ( ) ; }
Removes a segment .
19,997
protected JournalSegment < E > newSegment ( JournalSegmentFile segmentFile , JournalSegmentDescriptor descriptor ) { return new JournalSegment < > ( segmentFile , descriptor , storageLevel , maxEntrySize , indexDensity , namespace ) ; }
Creates a new segment instance .
19,998
void resetHead ( long index ) { for ( SegmentedJournalReader reader : readers ) { if ( reader . getNextIndex ( ) < index ) { reader . reset ( index ) ; } } }
Resets journal readers to the given head .
19,999
void resetTail ( long index ) { for ( SegmentedJournalReader reader : readers ) { if ( reader . getNextIndex ( ) >= index ) { reader . reset ( index ) ; } } }
Resets journal readers to the given tail .