idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
20,000 | public boolean isCompactable ( long index ) { Map . Entry < Long , JournalSegment < E > > segmentEntry = segments . floorEntry ( index ) ; return segmentEntry != null && segments . headMap ( segmentEntry . getValue ( ) . index ( ) ) . size ( ) > 0 ; } | Returns a boolean indicating whether a segment can be removed from the journal prior to the given index . |
20,001 | public long getCompactableIndex ( long index ) { Map . Entry < Long , JournalSegment < E > > segmentEntry = segments . floorEntry ( index ) ; return segmentEntry != null ? segmentEntry . getValue ( ) . index ( ) : 0 ; } | Returns the index of the last segment in the log . |
20,002 | public void report ( long arrivalTime ) { checkArgument ( arrivalTime >= 0 , "arrivalTime must not be negative" ) ; long latestHeartbeat = history . latestHeartbeatTime ( ) ; history . samples ( ) . addValue ( arrivalTime - latestHeartbeat ) ; history . setLatestHeartbeatTime ( arrivalTime ) ; } | Report a new heart beat for the specified node id . |
20,003 | public double phi ( ) { long latestHeartbeat = history . latestHeartbeatTime ( ) ; DescriptiveStatistics samples = history . samples ( ) ; if ( samples . getN ( ) < minSamples ) { return 0.0 ; } return computePhi ( samples , latestHeartbeat , System . currentTimeMillis ( ) ) ; } | Compute phi for the specified node id . |
20,004 | void register ( String type , BiConsumer < ProtocolRequest , ServerConnection > handler ) { handlers . put ( type , handler ) ; } | Registers a message type handler . |
20,005 | private void onMembershipChange ( ClusterMembershipEvent event ) { if ( event . type ( ) == ClusterMembershipEvent . Type . MEMBER_REMOVED ) { recoverTransactions ( transactions . entrySet ( ) . iterator ( ) , event . subject ( ) . id ( ) ) ; } } | Handles a cluster membership change event . |
20,006 | private void recoverTransactions ( AsyncIterator < Map . Entry < TransactionId , Versioned < TransactionInfo > > > iterator , MemberId memberId ) { iterator . next ( ) . thenAccept ( entry -> { if ( entry . getValue ( ) . value ( ) . coordinator . equals ( memberId ) ) { recoverTransaction ( entry . getKey ( ) , entry . getValue ( ) . value ( ) ) ; } recoverTransactions ( iterator , memberId ) ; } ) ; } | Recursively recovers transactions using the given iterator . |
20,007 | private void recoverTransaction ( TransactionId transactionId , TransactionInfo transactionInfo ) { switch ( transactionInfo . state ) { case PREPARING : completePreparingTransaction ( transactionId ) ; break ; case COMMITTING : completeCommittingTransaction ( transactionId ) ; break ; case ROLLING_BACK : completeRollingBackTransaction ( transactionId ) ; break ; default : break ; } } | Recovers and completes the given transaction . |
20,008 | @ SuppressWarnings ( "unchecked" ) private CompletableFuture < Void > completeTransaction ( TransactionId transactionId , TransactionState expectState , Function < TransactionInfo , TransactionInfo > updateFunction , Predicate < TransactionInfo > updatedPredicate , BiFunction < TransactionId , Transactional < ? > , CompletableFuture < Void > > completionFunction ) { return transactions . compute ( transactionId , ( id , info ) -> { if ( info == null ) { return null ; } else if ( info . state == expectState ) { return updateFunction . apply ( info ) ; } else { return info ; } } ) . thenCompose ( value -> { if ( value != null && updatedPredicate . test ( value . value ( ) ) ) { return Futures . allOf ( value . value ( ) . participants . stream ( ) . map ( participantInfo -> completeParticipant ( participantInfo , info -> completionFunction . apply ( transactionId , info ) ) ) ) . thenApply ( v -> null ) ; } return Futures . exceptionalFuture ( new TransactionException ( "Failed to acquire transaction lock" ) ) ; } ) ; } | Completes a transaction by modifying the transaction state to change ownership to this member and then completing the transaction based on the existing transaction state . |
20,009 | private DocumentPath getDocumentPath ( List < PathSegment > params ) { if ( params . isEmpty ( ) ) { return DocumentPath . ROOT ; } else { return DocumentPath . from ( params . stream ( ) . map ( PathSegment :: getPath ) . collect ( Collectors . toList ( ) ) ) ; } } | Returns a document path for the given path params . |
20,010 | public static HeapBytes allocate ( int size ) { if ( size > MAX_SIZE ) { throw new IllegalArgumentException ( "size cannot for HeapBytes cannot be greater than " + MAX_SIZE ) ; } return new HeapBytes ( ByteBuffer . allocate ( ( int ) size ) ) ; } | Allocates a new heap byte array . |
20,011 | public synchronized MemberId loadVote ( ) { String id = metadataBuffer . readString ( 8 ) ; return id != null ? MemberId . from ( id ) : null ; } | Loads the last vote for the server . |
20,012 | public CompletableFuture < E > nextEvent ( ) { E event = events . poll ( ) ; if ( event != null ) { return CompletableFuture . completedFuture ( event ) ; } else { CompletableFuture < E > future = new CompletableFuture < > ( ) ; futures . add ( future ) ; return future ; } } | Completes the given response with the next event . |
20,013 | public void addEvent ( E event ) { CompletableFuture < E > future = futures . poll ( ) ; if ( future != null ) { future . complete ( event ) ; } else { events . add ( event ) ; if ( events . size ( ) > 100 ) { events . remove ( ) ; } } } | Adds an event to the log . |
20,014 | public static MappedMemory allocate ( File file , FileChannel . MapMode mode , int size ) { if ( size > MAX_SIZE ) { throw new IllegalArgumentException ( "size cannot be greater than " + MAX_SIZE ) ; } return new MappedMemoryAllocator ( file , mode ) . allocate ( size ) ; } | Allocates memory mapped to a file on disk . |
20,015 | private String getEventLogName ( String name , String id ) { return String . format ( "%s-%s" , name , id ) ; } | Returns an event log name for the given identifier . |
20,016 | private void consumeNextEvent ( EventLog < LeadershipEventListener < String > , LeadershipEvent < String > > eventLog , String name , String id , AsyncResponse response ) { eventLog . nextEvent ( ) . whenComplete ( ( event , error ) -> { if ( error == null ) { if ( event . newLeadership ( ) . leader ( ) != null && event . newLeadership ( ) . leader ( ) . id ( ) . equals ( id ) ) { response . resume ( Response . ok ( new LeadershipResponse ( event . newLeadership ( ) ) ) . build ( ) ) ; } else if ( event . newLeadership ( ) . candidates ( ) . stream ( ) . noneMatch ( c -> c . equals ( id ) ) ) { getPrimitive ( name ) . thenCompose ( election -> election . removeListener ( eventLog . listener ( ) ) ) . whenComplete ( ( removeResult , removeError ) -> { response . resume ( Response . status ( Status . NOT_FOUND ) . build ( ) ) ; } ) ; } } else { response . resume ( Response . status ( Status . NOT_FOUND ) . build ( ) ) ; } } ) ; } | Recursively consumes events from the given event log until the next event for the given ID is located . |
20,017 | private CompletableFuture < MetadataResponse > getMetadata ( ) { CompletableFuture < MetadataResponse > future = new CompletableFuture < > ( ) ; connection . metadata ( MetadataRequest . builder ( ) . build ( ) ) . whenComplete ( ( response , error ) -> { if ( error == null ) { if ( response . status ( ) == RaftResponse . Status . OK ) { future . complete ( response ) ; } else { future . completeExceptionally ( response . error ( ) . createException ( ) ) ; } } else { future . completeExceptionally ( error ) ; } } ) ; return future ; } | Requests metadata from the cluster . |
20,018 | private void handleMembershipEvent ( GroupMembershipEvent event ) { post ( new ClusterMembershipEvent ( ClusterMembershipEvent . Type . valueOf ( event . type ( ) . name ( ) ) , event . member ( ) ) ) ; } | Handles a group membership event . |
20,019 | public static AtomixClusterBuilder builder ( String config , ClassLoader classLoader ) { return new AtomixClusterBuilder ( config ( withDefaultResources ( config ) , classLoader ) ) ; } | Returns a new Atomix builder . |
20,020 | private static ClusterConfig loadConfig ( File config , ClassLoader classLoader ) { return new ConfigMapper ( classLoader ) . loadResources ( ClusterConfig . class , config . getAbsolutePath ( ) ) ; } | Loads a configuration from the given file . |
20,021 | protected static ManagedMessagingService buildMessagingService ( ClusterConfig config ) { return new NettyMessagingService ( config . getClusterId ( ) , config . getNodeConfig ( ) . getAddress ( ) , config . getMessagingConfig ( ) ) ; } | Builds a default messaging service . |
20,022 | protected static ManagedUnicastService buildUnicastService ( ClusterConfig config ) { return new NettyUnicastService ( config . getNodeConfig ( ) . getAddress ( ) , config . getMessagingConfig ( ) ) ; } | Builds a default unicast service . |
20,023 | protected static ManagedBroadcastService buildBroadcastService ( ClusterConfig config ) { return NettyBroadcastService . builder ( ) . withLocalAddress ( config . getNodeConfig ( ) . getAddress ( ) ) . withGroupAddress ( new Address ( config . getMulticastConfig ( ) . getGroup ( ) . getHostAddress ( ) , config . getMulticastConfig ( ) . getPort ( ) , config . getMulticastConfig ( ) . getGroup ( ) ) ) . withEnabled ( config . getMulticastConfig ( ) . isEnabled ( ) ) . build ( ) ; } | Builds a default broadcast service . |
20,024 | @ SuppressWarnings ( "unchecked" ) protected static NodeDiscoveryProvider buildLocationProvider ( ClusterConfig config ) { NodeDiscoveryConfig discoveryProviderConfig = config . getDiscoveryConfig ( ) ; if ( discoveryProviderConfig != null ) { return discoveryProviderConfig . getType ( ) . newProvider ( discoveryProviderConfig ) ; } if ( config . getMulticastConfig ( ) . isEnabled ( ) ) { return new MulticastDiscoveryProvider ( new MulticastDiscoveryConfig ( ) ) ; } else { return new BootstrapDiscoveryProvider ( Collections . emptyList ( ) ) ; } } | Builds a member location provider . |
20,025 | @ SuppressWarnings ( "unchecked" ) protected static GroupMembershipProtocol buildMembershipProtocol ( ClusterConfig config ) { return config . getProtocolConfig ( ) . getType ( ) . newProtocol ( config . getProtocolConfig ( ) ) ; } | Builds the group membership protocol . |
20,026 | protected static ManagedClusterMembershipService buildClusterMembershipService ( ClusterConfig config , BootstrapService bootstrapService , NodeDiscoveryProvider discoveryProvider , GroupMembershipProtocol membershipProtocol , Version version ) { Member localMember = Member . builder ( ) . withId ( config . getNodeConfig ( ) . getId ( ) ) . withAddress ( config . getNodeConfig ( ) . getAddress ( ) ) . withHostId ( config . getNodeConfig ( ) . getHostId ( ) ) . withRackId ( config . getNodeConfig ( ) . getRackId ( ) ) . withZoneId ( config . getNodeConfig ( ) . getZoneId ( ) ) . withProperties ( config . getNodeConfig ( ) . getProperties ( ) ) . build ( ) ; return new DefaultClusterMembershipService ( localMember , version , new DefaultNodeDiscoveryService ( bootstrapService , localMember , discoveryProvider ) , bootstrapService , membershipProtocol ) ; } | Builds a cluster service . |
20,027 | protected static ManagedClusterCommunicationService buildClusterMessagingService ( ClusterMembershipService membershipService , MessagingService messagingService , UnicastService unicastService ) { return new DefaultClusterCommunicationService ( membershipService , messagingService , unicastService ) ; } | Builds a cluster messaging service . |
20,028 | public CompletableFuture < Void > open ( ) { return primaryElection . getTerm ( ) . thenAccept ( this :: changeRole ) . thenRun ( ( ) -> service . init ( this ) ) ; } | Opens the service context . |
20,029 | public long setTimestamp ( long timestamp ) { this . currentTimestamp = timestamp ; service . tick ( WallClockTimestamp . from ( timestamp ) ) ; return currentTimestamp ; } | Sets the current timestamp . |
20,030 | public boolean nextIndex ( long index ) { if ( operationIndex + 1 == index ) { currentOperation = OperationType . COMMAND ; operationIndex ++ ; return true ; } return false ; } | Increments the current index and returns true if the given index is the next index . |
20,031 | public void resetIndex ( long index , long timestamp ) { currentOperation = OperationType . COMMAND ; operationIndex = index ; currentIndex = index ; currentTimestamp = timestamp ; setCommitIndex ( index ) ; service . tick ( new WallClockTimestamp ( currentTimestamp ) ) ; } | Resets the current index to the given index and timestamp . |
20,032 | public PrimaryBackupSession createSession ( long sessionId , MemberId memberId ) { PrimaryBackupSession session = new PrimaryBackupSession ( SessionId . from ( sessionId ) , memberId , service . serializer ( ) , this ) ; if ( sessions . putIfAbsent ( sessionId , session ) == null ) { service . register ( session ) ; } return session ; } | Creates a service session . |
20,033 | public PrimaryBackupSession getOrCreateSession ( long sessionId , MemberId memberId ) { PrimaryBackupSession session = sessions . get ( sessionId ) ; if ( session == null ) { session = createSession ( sessionId , memberId ) ; } return session ; } | Gets or creates a service session . |
20,034 | public void expireSession ( long sessionId ) { PrimaryBackupSession session = sessions . remove ( sessionId ) ; if ( session != null ) { log . debug ( "Expiring session {}" , session . sessionId ( ) ) ; session . expire ( ) ; service . expire ( session . sessionId ( ) ) ; } } | Expires the session with the given ID . |
20,035 | public void closeSession ( long sessionId ) { PrimaryBackupSession session = sessions . remove ( sessionId ) ; if ( session != null ) { log . debug ( "Closing session {}" , session . sessionId ( ) ) ; session . close ( ) ; service . close ( session . sessionId ( ) ) ; } } | Closes the session with the given ID . |
20,036 | public CompletableFuture < Void > close ( ) { CompletableFuture < Void > future = new CompletableFuture < > ( ) ; threadContext . execute ( ( ) -> { try { clusterMembershipService . removeListener ( membershipEventListener ) ; primaryElection . removeListener ( primaryElectionListener ) ; role . close ( ) ; } finally { future . complete ( null ) ; } } ) ; return future . thenRunAsync ( ( ) -> threadContext . close ( ) ) ; } | Closes the service . |
20,037 | public CompletableFuture < ConsumeResponse > consume ( ConsumeRequest request ) { logRequest ( request ) ; return CompletableFuture . completedFuture ( logResponse ( ConsumeResponse . error ( ) ) ) ; } | Handles a consume request . |
20,038 | private void handleMembershipChange ( ClusterMembershipEvent event ) { if ( event . type ( ) == ClusterMembershipEvent . Type . MEMBER_ADDED ) { bootstrap ( event . subject ( ) ) ; } else if ( event . type ( ) == ClusterMembershipEvent . Type . MEMBER_REMOVED ) { threadContext . execute ( ( ) -> { PartitionGroupMembership systemGroup = this . systemGroup ; if ( systemGroup != null && systemGroup . members ( ) . contains ( event . subject ( ) . id ( ) ) ) { Set < MemberId > newMembers = Sets . newHashSet ( systemGroup . members ( ) ) ; newMembers . remove ( event . subject ( ) . id ( ) ) ; PartitionGroupMembership newMembership = new PartitionGroupMembership ( systemGroup . group ( ) , systemGroup . config ( ) , ImmutableSet . copyOf ( newMembers ) , true ) ; this . systemGroup = newMembership ; post ( new PartitionGroupMembershipEvent ( MEMBERS_CHANGED , newMembership ) ) ; } groups . values ( ) . forEach ( group -> { if ( group . members ( ) . contains ( event . subject ( ) . id ( ) ) ) { Set < MemberId > newMembers = Sets . newHashSet ( group . members ( ) ) ; newMembers . remove ( event . subject ( ) . id ( ) ) ; PartitionGroupMembership newMembership = new PartitionGroupMembership ( group . group ( ) , group . config ( ) , ImmutableSet . copyOf ( newMembers ) , false ) ; groups . put ( group . group ( ) , newMembership ) ; post ( new PartitionGroupMembershipEvent ( MEMBERS_CHANGED , newMembership ) ) ; } } ) ; } ) ; } } | Handles a cluster membership change . |
20,039 | private CompletableFuture < Void > bootstrap ( int attempt , CompletableFuture < Void > future ) { Futures . allOf ( membershipService . getMembers ( ) . stream ( ) . filter ( node -> ! node . id ( ) . equals ( membershipService . getLocalMember ( ) . id ( ) ) ) . map ( node -> bootstrap ( node ) ) . collect ( Collectors . toList ( ) ) ) . whenComplete ( ( result , error ) -> { if ( error == null ) { if ( systemGroup == null ) { LOGGER . warn ( "Failed to locate management group via bootstrap nodes. Please ensure partition " + "groups are configured either locally or remotely and the node is able to reach partition group members." ) ; threadContext . schedule ( Duration . ofSeconds ( FIBONACCI_NUMBERS [ Math . min ( attempt , 4 ) ] ) , ( ) -> bootstrap ( attempt + 1 , future ) ) ; } else if ( groups . isEmpty ( ) && attempt < MAX_PARTITION_GROUP_ATTEMPTS ) { LOGGER . warn ( "Failed to locate partition group(s) via bootstrap nodes. Please ensure partition " + "groups are configured either locally or remotely and the node is able to reach partition group members." ) ; threadContext . schedule ( Duration . ofSeconds ( FIBONACCI_NUMBERS [ Math . min ( attempt , 4 ) ] ) , ( ) -> bootstrap ( attempt + 1 , future ) ) ; } else { future . complete ( null ) ; } } else { future . completeExceptionally ( error ) ; } } ) ; return future ; } | Recursively bootstraps the service retrying if necessary until a system partition group is found . |
20,040 | @ SuppressWarnings ( "unchecked" ) private CompletableFuture < Void > bootstrap ( Member member , CompletableFuture < Void > future ) { LOGGER . debug ( "{} - Bootstrapping from member {}" , membershipService . getLocalMember ( ) . id ( ) , member ) ; messagingService . < PartitionGroupInfo , PartitionGroupInfo > send ( BOOTSTRAP_SUBJECT , new PartitionGroupInfo ( membershipService . getLocalMember ( ) . id ( ) , systemGroup , Lists . newArrayList ( groups . values ( ) ) ) , serializer :: encode , serializer :: decode , member . id ( ) ) . whenCompleteAsync ( ( info , error ) -> { if ( error == null ) { try { updatePartitionGroups ( info ) ; future . complete ( null ) ; } catch ( Exception e ) { future . completeExceptionally ( e ) ; } } else { error = Throwables . getRootCause ( error ) ; if ( error instanceof MessagingException . NoRemoteHandler || error instanceof TimeoutException ) { threadContext . schedule ( Duration . ofSeconds ( 1 ) , ( ) -> bootstrap ( member , future ) ) ; } else { LOGGER . debug ( "{} - Failed to bootstrap from member {}" , membershipService . getLocalMember ( ) . id ( ) , member , error ) ; future . complete ( null ) ; } } } , threadContext ) ; return future ; } | Bootstraps the service from the given node . |
20,041 | CompletableFuture < Partition > join ( PartitionManagementService managementService , ThreadContextFactory threadFactory ) { election = managementService . getElectionService ( ) . getElectionFor ( partitionId ) ; server = new PrimaryBackupPartitionServer ( this , managementService , memberGroupProvider , threadFactory ) ; client = new PrimaryBackupPartitionClient ( this , managementService , threadFactory ) ; return server . start ( ) . thenCompose ( v -> client . start ( ) ) . thenApply ( v -> this ) ; } | Joins the primary - backup partition . |
20,042 | CompletableFuture < Partition > connect ( PartitionManagementService managementService , ThreadContextFactory threadFactory ) { election = managementService . getElectionService ( ) . getElectionFor ( partitionId ) ; client = new PrimaryBackupPartitionClient ( this , managementService , threadFactory ) ; return client . start ( ) . thenApply ( v -> this ) ; } | Connects to the primary - backup partition . |
20,043 | public CompletableFuture < Void > close ( ) { if ( client == null ) { return CompletableFuture . completedFuture ( null ) ; } CompletableFuture < Void > future = new CompletableFuture < > ( ) ; client . stop ( ) . whenComplete ( ( clientResult , clientError ) -> { if ( server != null ) { server . stop ( ) . whenComplete ( ( serverResult , serverError ) -> { future . complete ( null ) ; } ) ; } else { future . complete ( null ) ; } } ) ; return future ; } | Closes the primary - backup partition . |
20,044 | private boolean isPolymorphicType ( Class < ? > clazz ) { return polymorphicTypes . stream ( ) . anyMatch ( polymorphicType -> polymorphicType . getConfigClass ( ) == clazz ) ; } | Returns a boolean indicating whether the given class is a polymorphic type . |
20,045 | private static Map < Method , EventType > findMethods ( Class < ? > type ) { Map < Method , EventType > events = new HashMap < > ( ) ; for ( Method method : type . getDeclaredMethods ( ) ) { Event event = method . getAnnotation ( Event . class ) ; if ( event != null ) { String name = event . value ( ) . equals ( "" ) ? method . getName ( ) : event . value ( ) ; events . put ( method , EventType . from ( name ) ) ; } } for ( Class < ? > iface : type . getInterfaces ( ) ) { events . putAll ( findMethods ( iface ) ) ; } return events ; } | Recursively finds events defined by the given type and its implemented interfaces . |
20,046 | public SerializerBuilder addSerializer ( com . esotericsoftware . kryo . Serializer serializer , Class < ? > ... types ) { namespaceBuilder . register ( serializer , types ) ; return this ; } | Adds a serializer to the builder . |
20,047 | public void reset ( MemberId leader , Collection < MemberId > servers ) { selector . reset ( leader , servers ) ; } | Resets the member selector . |
20,048 | public CompletableFuture < OpenSessionResponse > openSession ( OpenSessionRequest request ) { CompletableFuture < OpenSessionResponse > future = new CompletableFuture < > ( ) ; if ( context . isCurrentContext ( ) ) { sendRequest ( request , protocol :: openSession , future ) ; } else { context . execute ( ( ) -> sendRequest ( request , protocol :: openSession , future ) ) ; } return future ; } | Sends an open session request to the given node . |
20,049 | public CompletableFuture < CloseSessionResponse > closeSession ( CloseSessionRequest request ) { CompletableFuture < CloseSessionResponse > future = new CompletableFuture < > ( ) ; if ( context . isCurrentContext ( ) ) { sendRequest ( request , protocol :: closeSession , future ) ; } else { context . execute ( ( ) -> sendRequest ( request , protocol :: closeSession , future ) ) ; } return future ; } | Sends a close session request to the given node . |
20,050 | public CompletableFuture < KeepAliveResponse > keepAlive ( KeepAliveRequest request ) { CompletableFuture < KeepAliveResponse > future = new CompletableFuture < > ( ) ; if ( context . isCurrentContext ( ) ) { sendRequest ( request , protocol :: keepAlive , future ) ; } else { context . execute ( ( ) -> sendRequest ( request , protocol :: keepAlive , future ) ) ; } return future ; } | Sends a keep alive request to the given node . |
20,051 | public CompletableFuture < QueryResponse > query ( QueryRequest request ) { CompletableFuture < QueryResponse > future = new CompletableFuture < > ( ) ; if ( context . isCurrentContext ( ) ) { sendRequest ( request , protocol :: query , future ) ; } else { context . execute ( ( ) -> sendRequest ( request , protocol :: query , future ) ) ; } return future ; } | Sends a query request to the given node . |
20,052 | public CompletableFuture < CommandResponse > command ( CommandRequest request ) { CompletableFuture < CommandResponse > future = new CompletableFuture < > ( ) ; if ( context . isCurrentContext ( ) ) { sendRequest ( request , protocol :: command , future ) ; } else { context . execute ( ( ) -> sendRequest ( request , protocol :: command , future ) ) ; } return future ; } | Sends a command request to the given node . |
20,053 | public CompletableFuture < MetadataResponse > metadata ( MetadataRequest request ) { CompletableFuture < MetadataResponse > future = new CompletableFuture < > ( ) ; if ( context . isCurrentContext ( ) ) { sendRequest ( request , protocol :: metadata , future ) ; } else { context . execute ( ( ) -> sendRequest ( request , protocol :: metadata , future ) ) ; } return future ; } | Sends a metadata request to the given node . |
20,054 | public void delete ( ) { try { close ( ) ; Files . delete ( file . toPath ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Deletes the underlying file . |
20,055 | private CompletableFuture < Iterator < T > > batch ( ) { return batch . thenCompose ( iterator -> { if ( iterator != null && ! iterator . hasNext ( ) ) { batch = fetch ( iterator . position ( ) ) ; return batch . thenApply ( Function . identity ( ) ) ; } return CompletableFuture . completedFuture ( iterator ) ; } ) ; } | Returns the current batch iterator or lazily fetches the next batch from the cluster . |
20,056 | private CompletableFuture < IteratorBatch < T > > fetch ( int position ) { return openFuture . thenCompose ( initialBatch -> { if ( ! initialBatch . complete ( ) ) { return client . applyOn ( partitionId , service -> nextFunction . next ( service , initialBatch . id ( ) , position ) ) . thenCompose ( nextBatch -> { if ( nextBatch == null ) { return close ( ) . thenApply ( v -> null ) ; } return CompletableFuture . completedFuture ( nextBatch ) ; } ) ; } return CompletableFuture . completedFuture ( null ) ; } ) ; } | Fetches the next batch of entries from the cluster . |
20,057 | public MulticastConfig setGroup ( String group ) { try { InetAddress address = InetAddress . getByName ( group ) ; if ( ! address . isMulticastAddress ( ) ) { throw new ConfigurationException ( "Invalid multicast group " + group ) ; } return setGroup ( address ) ; } catch ( UnknownHostException e ) { throw new ConfigurationException ( "Failed to locate multicast group" , e ) ; } } | Sets the multicast group . |
20,058 | private void rescheduleTask ( AtomicReference < TimerTask > taskRef , long millis ) { ProcessorTask newTask = new ProcessorTask ( ) ; timer . schedule ( newTask , millis ) ; swapAndCancelTask ( taskRef , newTask ) ; } | Reschedules the specified task cancelling existing one if applicable . |
20,059 | private void swapAndCancelTask ( AtomicReference < TimerTask > taskRef , TimerTask newTask ) { TimerTask oldTask = taskRef . getAndSet ( newTask ) ; if ( oldTask != null ) { oldTask . cancel ( ) ; } } | Sets the new task and attempts to cancelTask the old one . |
20,060 | private List < T > finalizeCurrentBatch ( ) { List < T > finalizedList ; synchronized ( items ) { finalizedList = ImmutableList . copyOf ( items ) ; items . clear ( ) ; cancelTask ( maxTask ) ; cancelTask ( idleTask ) ; } return finalizedList ; } | Returns an immutable copy of the existing items and clear the list . |
20,061 | protected Set < E > set ( ) { return elements . entrySet ( ) . stream ( ) . filter ( entry -> ! entry . getValue ( ) . isTombstone ( ) ) . map ( entry -> decode ( entry . getKey ( ) ) ) . collect ( Collectors . toSet ( ) ) ; } | Returns the computed set . |
20,062 | private String encode ( Object element ) { return BaseEncoding . base16 ( ) . encode ( elementSerializer . encode ( element ) ) ; } | Encodes the given element to a string for internal storage . |
20,063 | protected E decode ( String element ) { return elementSerializer . decode ( BaseEncoding . base16 ( ) . decode ( element ) ) ; } | Decodes the given element from a string . |
20,064 | private void updateElements ( Map < String , SetElement > elements ) { for ( SetElement element : elements . values ( ) ) { if ( element . isTombstone ( ) ) { if ( remove ( element ) ) { eventListeners . forEach ( listener -> listener . event ( new SetDelegateEvent < > ( SetDelegateEvent . Type . REMOVE , decode ( element . value ( ) ) ) ) ) ; } } else { if ( add ( element ) ) { eventListeners . forEach ( listener -> listener . event ( new SetDelegateEvent < > ( SetDelegateEvent . Type . ADD , decode ( element . value ( ) ) ) ) ) ; } } } } | Updates the set elements . |
20,065 | public PrimaryBackupSessionClient . Builder sessionBuilder ( String primitiveName , PrimitiveType primitiveType , ServiceConfig serviceConfig ) { byte [ ] configBytes = Serializer . using ( primitiveType . namespace ( ) ) . encode ( serviceConfig ) ; return new PrimaryBackupSessionClient . Builder ( ) { public SessionClient build ( ) { Supplier < CompletableFuture < SessionClient > > proxyBuilder = ( ) -> sessionIdService . nextSessionId ( ) . thenApply ( sessionId -> new PrimaryBackupSessionClient ( clientName , partitionId , sessionId , primitiveType , new PrimitiveDescriptor ( primitiveName , primitiveType . name ( ) , configBytes , numBackups , replication ) , clusterMembershipService , PrimaryBackupClient . this . protocol , primaryElection , threadContextFactory . createContext ( ) ) ) ; SessionClient proxy ; ThreadContext context = threadContextFactory . createContext ( ) ; if ( recovery == Recovery . RECOVER ) { proxy = new RecoveringSessionClient ( clientName , partitionId , primitiveName , primitiveType , proxyBuilder , context ) ; } else { proxy = Futures . get ( proxyBuilder . get ( ) ) ; } if ( maxRetries > 0 ) { proxy = new RetryingSessionClient ( proxy , context , maxRetries , retryDelay ) ; } return new BlockingAwareSessionClient ( proxy , context ) ; } } ; } | Creates a new primary backup proxy session builder . |
20,066 | public CompletableFuture < Void > close ( ) { threadContext . close ( ) ; if ( closeOnStop ) { threadContextFactory . close ( ) ; } return CompletableFuture . completedFuture ( null ) ; } | Closes the primary - backup client . |
20,067 | private void resetJoinTimer ( ) { cancelJoinTimer ( ) ; joinTimeout = raft . getThreadContext ( ) . schedule ( raft . getElectionTimeout ( ) . multipliedBy ( 2 ) , ( ) -> { join ( getActiveMemberStates ( ) . iterator ( ) ) ; } ) ; } | Resets the join timer . |
20,068 | CompletableFuture < Void > produce ( byte [ ] bytes ) { return session . producer ( ) . append ( bytes ) . thenApply ( v -> null ) ; } | Produces the given bytes to the partition . |
20,069 | private void configure ( OperationId operationId , Method method , ServiceExecutor executor ) { if ( method . getReturnType ( ) == Void . TYPE ) { if ( method . getParameterTypes ( ) . length == 0 ) { executor . register ( operationId , ( ) -> { try { method . invoke ( this ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { throw new PrimitiveException . ServiceException ( e ) ; } } ) ; } else { executor . register ( operationId , args -> { try { method . invoke ( this , ( Object [ ] ) args . value ( ) ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { throw new PrimitiveException . ServiceException ( e ) ; } } ) ; } } else { if ( method . getParameterTypes ( ) . length == 0 ) { executor . register ( operationId , ( ) -> { try { return method . invoke ( this ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { throw new PrimitiveException . ServiceException ( e ) ; } } ) ; } else { executor . register ( operationId , args -> { try { return method . invoke ( this , ( Object [ ] ) args . value ( ) ) ; } catch ( IllegalAccessException | InvocationTargetException e ) { throw new PrimitiveException . ServiceException ( e ) ; } } ) ; } } } | Configures the given operation on the given executor . |
20,070 | public boolean lock ( String id ) { File file = new File ( directory , String . format ( ".%s.lock" , prefix ) ) ; try { if ( file . createNewFile ( ) ) { try ( FileBuffer buffer = FileBuffer . allocate ( file ) ) { buffer . writeString ( id ) . flush ( ) ; } return true ; } else { try ( FileBuffer buffer = FileBuffer . allocate ( file ) ) { String lock = buffer . readString ( ) ; return lock != null && lock . equals ( id ) ; } } } catch ( IOException e ) { throw new StorageException ( "Failed to acquire storage lock" ) ; } } | Attempts to acquire a lock on the storage directory . |
20,071 | private void deleteFiles ( Predicate < File > predicate ) { directory . mkdirs ( ) ; for ( File file : directory . listFiles ( f -> f . isFile ( ) && predicate . test ( f ) ) ) { try { Files . delete ( file . toPath ( ) ) ; } catch ( IOException e ) { } } } | Deletes file in the storage directory that match the given predicate . |
20,072 | private void drainCommands ( long sequenceNumber , RaftSession session ) { long nextSequence = session . nextRequestSequence ( ) ; for ( long i = sequenceNumber ; i < nextSequence ; i ++ ) { PendingCommand nextCommand = session . removeCommand ( i ) ; if ( nextCommand != null ) { commitCommand ( nextCommand . request ( ) , nextCommand . future ( ) ) ; } } PendingCommand nextCommand = session . removeCommand ( nextSequence ) ; while ( nextCommand != null ) { commitCommand ( nextCommand . request ( ) , nextCommand . future ( ) ) ; session . setRequestSequence ( nextSequence ) ; nextSequence = session . nextRequestSequence ( ) ; nextCommand = session . removeCommand ( nextSequence ) ; } } | Sequentially drains pending commands from the session s command request queue . |
20,073 | private void commitCommand ( CommandRequest request , CompletableFuture < CommandResponse > future ) { final long term = raft . getTerm ( ) ; final long timestamp = System . currentTimeMillis ( ) ; CommandEntry command = new CommandEntry ( term , timestamp , request . session ( ) , request . sequenceNumber ( ) , request . operation ( ) ) ; appendAndCompact ( command ) . whenCompleteAsync ( ( entry , error ) -> { if ( error != null ) { Throwable cause = Throwables . getRootCause ( error ) ; if ( Throwables . getRootCause ( error ) instanceof StorageException . TooLarge ) { log . warn ( "Failed to append command {}" , command , cause ) ; future . complete ( CommandResponse . builder ( ) . withStatus ( RaftResponse . Status . ERROR ) . withError ( RaftError . Type . PROTOCOL_ERROR ) . build ( ) ) ; } else { future . complete ( CommandResponse . builder ( ) . withStatus ( RaftResponse . Status . ERROR ) . withError ( RaftError . Type . COMMAND_FAILURE ) . build ( ) ) ; } return ; } appender . appendEntries ( entry . index ( ) ) . whenComplete ( ( commitIndex , commitError ) -> { raft . checkThread ( ) ; if ( isRunning ( ) ) { if ( commitError == null ) { raft . getServiceManager ( ) . < OperationResult > apply ( entry . index ( ) ) . whenComplete ( ( r , e ) -> { completeOperation ( r , CommandResponse . builder ( ) , e , future ) ; } ) ; } else { future . complete ( CommandResponse . builder ( ) . withStatus ( RaftResponse . Status . ERROR ) . withError ( RaftError . Type . COMMAND_FAILURE ) . build ( ) ) ; } } else { future . complete ( CommandResponse . builder ( ) . withStatus ( RaftResponse . Status . ERROR ) . withError ( RaftError . Type . COMMAND_FAILURE ) . build ( ) ) ; } } ) ; } , raft . getThreadContext ( ) ) ; } | Commits a command . |
20,074 | private void failPendingCommands ( ) { for ( RaftSession session : raft . getSessions ( ) . getSessions ( ) ) { for ( PendingCommand command : session . clearCommands ( ) ) { command . future ( ) . complete ( logResponse ( CommandResponse . builder ( ) . withStatus ( RaftResponse . Status . ERROR ) . withError ( RaftError . Type . COMMAND_FAILURE , "Request sequence number " + command . request ( ) . sequenceNumber ( ) + " out of sequence" ) . withLastSequence ( session . getRequestSequence ( ) ) . build ( ) ) ) ; } } } | Fails pending commands . |
20,075 | public < T > SetUpdate < T > map ( Function < E , T > mapper ) { return new SetUpdate < T > ( type , mapper . apply ( element ) ) ; } | Maps the value of the update to another type . |
20,076 | private void handleDiscoveryEvent ( NodeDiscoveryEvent event ) { switch ( event . type ( ) ) { case JOIN : handleJoinEvent ( event . subject ( ) ) ; break ; case LEAVE : handleLeaveEvent ( event . subject ( ) ) ; break ; default : throw new AssertionError ( ) ; } } | Handles a member location event . |
20,077 | private CompletableFuture < Void > sendHeartbeats ( ) { checkMetadata ( ) ; Stream < GossipMember > clusterMembers = members . values ( ) . stream ( ) . filter ( member -> ! member . id ( ) . equals ( localMember . id ( ) ) ) ; Stream < GossipMember > providerMembers = discoveryService . getNodes ( ) . stream ( ) . filter ( node -> ! members . containsKey ( MemberId . from ( node . id ( ) . id ( ) ) ) ) . map ( node -> new GossipMember ( MemberId . from ( node . id ( ) . id ( ) ) , node . address ( ) ) ) ; return Futures . allOf ( Stream . concat ( clusterMembers , providerMembers ) . map ( member -> { LOGGER . trace ( "{} - Sending heartbeat: {}" , localMember . id ( ) , member ) ; return sendHeartbeat ( member ) . exceptionally ( v -> null ) ; } ) . collect ( Collectors . toList ( ) ) ) . thenApply ( v -> null ) ; } | Sends heartbeats to all peers . |
20,078 | private CompletableFuture < Void > sendHeartbeat ( GossipMember member ) { return bootstrapService . getMessagingService ( ) . sendAndReceive ( member . address ( ) , HEARTBEAT_MESSAGE , SERIALIZER . encode ( localMember ) ) . whenCompleteAsync ( ( response , error ) -> { if ( error == null ) { Collection < GossipMember > remoteMembers = SERIALIZER . decode ( response ) ; for ( GossipMember remoteMember : remoteMembers ) { if ( ! remoteMember . id ( ) . equals ( localMember . id ( ) ) ) { updateMember ( remoteMember , remoteMember . id ( ) . equals ( member . id ( ) ) ) ; } } } else { LOGGER . debug ( "{} - Sending heartbeat to {} failed" , localMember . id ( ) , member , error ) ; if ( member . isReachable ( ) ) { member . setReachable ( false ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . REACHABILITY_CHANGED , member ) ) ; } PhiAccrualFailureDetector failureDetector = failureDetectors . computeIfAbsent ( member . id ( ) , n -> new PhiAccrualFailureDetector ( ) ) ; double phi = failureDetector . phi ( ) ; if ( phi >= config . getPhiFailureThreshold ( ) || ( phi == 0.0 && System . currentTimeMillis ( ) - failureDetector . lastUpdated ( ) > config . getFailureTimeout ( ) . toMillis ( ) ) ) { if ( members . remove ( member . id ( ) ) != null ) { failureDetectors . remove ( member . id ( ) ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . MEMBER_REMOVED , member ) ) ; } } } } , heartbeatScheduler ) . exceptionally ( e -> null ) . thenApply ( v -> null ) ; } | Sends a heartbeat to the given peer . |
20,079 | private byte [ ] handleHeartbeat ( Address address , byte [ ] message ) { GossipMember remoteMember = SERIALIZER . decode ( message ) ; LOGGER . trace ( "{} - Received heartbeat: {}" , localMember . id ( ) , remoteMember ) ; failureDetectors . computeIfAbsent ( remoteMember . id ( ) , n -> new PhiAccrualFailureDetector ( ) ) . report ( ) ; updateMember ( remoteMember , true ) ; return SERIALIZER . encode ( Lists . newArrayList ( members . values ( ) . stream ( ) . filter ( member -> member . isReachable ( ) ) . collect ( Collectors . toList ( ) ) ) ) ; } | Handles a heartbeat message . |
20,080 | private void updateMember ( GossipMember remoteMember , boolean direct ) { GossipMember localMember = members . get ( remoteMember . id ( ) ) ; if ( localMember == null ) { remoteMember . setActive ( true ) ; remoteMember . setReachable ( true ) ; members . put ( remoteMember . id ( ) , remoteMember ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . MEMBER_ADDED , remoteMember ) ) ; } else if ( ! Objects . equals ( localMember . version ( ) , remoteMember . version ( ) ) ) { members . remove ( localMember . id ( ) ) ; localMember . setReachable ( false ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . REACHABILITY_CHANGED , localMember ) ) ; localMember . setActive ( false ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . MEMBER_REMOVED , localMember ) ) ; members . put ( remoteMember . id ( ) , remoteMember ) ; remoteMember . setActive ( true ) ; remoteMember . setReachable ( true ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . MEMBER_ADDED , remoteMember ) ) ; } else if ( ! Objects . equals ( localMember . properties ( ) , remoteMember . properties ( ) ) ) { if ( ! localMember . isReachable ( ) ) { localMember . setReachable ( true ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . REACHABILITY_CHANGED , localMember ) ) ; } localMember . properties ( ) . putAll ( remoteMember . properties ( ) ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . METADATA_CHANGED , localMember ) ) ; } else if ( ! localMember . isReachable ( ) && direct ) { localMember . setReachable ( true ) ; localMember . setTerm ( localMember . getTerm ( ) + 1 ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . REACHABILITY_CHANGED , localMember ) ) ; } else if ( ! localMember . isReachable ( ) && remoteMember . getTerm ( ) > localMember . getTerm ( ) ) { localMember . setReachable ( true ) ; localMember . setTerm ( remoteMember . getTerm ( ) ) ; post ( new GroupMembershipEvent ( GroupMembershipEvent . Type . REACHABILITY_CHANGED , localMember ) ) ; } } | Updates the state of the given member . |
20,081 | public NodeConfig setAddress ( Address address ) { this . host = address . host ( ) ; this . port = address . port ( ) ; return this ; } | Sets the node address . |
20,082 | public boolean isNewerThan ( UpdateEntry other ) { return other == null || other . value == null || ( value != null && value . isNewerThan ( other . value ) ) ; } | Returns if this entry is newer than other entry . |
20,083 | public DocumentPath childPath ( ) { if ( pathElements . size ( ) <= 1 ) { return null ; } return new DocumentPath ( this . pathElements . subList ( pathElements . size ( ) - 1 , pathElements . size ( ) ) ) ; } | Returns the relative path to the given node . |
20,084 | public DocumentPath parent ( ) { if ( pathElements . size ( ) <= 1 ) { return null ; } return new DocumentPath ( this . pathElements . subList ( 0 , pathElements . size ( ) - 1 ) ) ; } | Returns a path for the parent of this node . |
20,085 | public static DocumentPath leastCommonAncestor ( Collection < DocumentPath > paths ) { if ( paths . isEmpty ( ) ) { return null ; } return DocumentPath . from ( StringUtils . getCommonPrefix ( paths . stream ( ) . map ( DocumentPath :: toString ) . toArray ( String [ ] :: new ) ) ) ; } | Returns the path that points to the least common ancestor of the specified collection of paths . |
20,086 | public long get ( int slots ) { checkArgument ( slots <= windowSlots , "Requested window must be less than the total window slots" ) ; long sum = 0 ; for ( int i = 0 ; i < slots ; i ++ ) { int currentIndex = headSlot - i ; if ( currentIndex < 0 ) { currentIndex = counters . size ( ) + currentIndex ; } sum += counters . get ( currentIndex ) . get ( ) ; } return sum ; } | Gets the total count for the last N window slots . |
20,087 | public < U > Leader < U > map ( Function < T , U > mapper ) { return new Leader < > ( mapper . apply ( id ) , term , termStartTime ) ; } | Converts the leader identifier using the given mapping function . |
20,088 | public < U > Leadership < U > map ( Function < T , U > mapper ) { return new Leadership < > ( leader != null ? leader . map ( mapper ) : null , candidates . stream ( ) . map ( mapper ) . collect ( Collectors . toList ( ) ) ) ; } | Maps the leadership identifiers using the given mapper . |
20,089 | private synchronized void changeState ( PrimitiveState state ) { if ( this . state != state ) { this . state = state ; stateChangeListeners . forEach ( l -> threadContext . execute ( ( ) -> l . accept ( state ) ) ) ; } } | Changes the current session state . |
20,090 | private CompletableFuture < PrimaryTerm > term ( ) { CompletableFuture < PrimaryTerm > future = new CompletableFuture < > ( ) ; threadContext . execute ( ( ) -> { if ( term != null ) { future . complete ( term ) ; } else { primaryElection . getTerm ( ) . whenCompleteAsync ( ( term , error ) -> { if ( term != null ) { this . term = term ; future . complete ( term ) ; } else { future . completeExceptionally ( new PrimitiveException . Unavailable ( ) ) ; } } ) ; } } ) ; return future ; } | Returns the current primary term . |
20,091 | @ SuppressWarnings ( "unchecked" ) private static ManagedPartitionGroup buildSystemPartitionGroup ( AtomixConfig config ) { PartitionGroupConfig < ? > partitionGroupConfig = config . getManagementGroup ( ) ; if ( partitionGroupConfig == null ) { return null ; } return partitionGroupConfig . getType ( ) . newPartitionGroup ( partitionGroupConfig ) ; } | Builds the core partition group . |
20,092 | @ SuppressWarnings ( "unchecked" ) private static ManagedPartitionService buildPartitionService ( AtomixConfig config , ClusterMembershipService clusterMembershipService , ClusterCommunicationService messagingService , AtomixRegistry registry ) { List < ManagedPartitionGroup > partitionGroups = new ArrayList < > ( ) ; for ( PartitionGroupConfig < ? > partitionGroupConfig : config . getPartitionGroups ( ) . values ( ) ) { partitionGroups . add ( partitionGroupConfig . getType ( ) . newPartitionGroup ( partitionGroupConfig ) ) ; } return new DefaultPartitionService ( clusterMembershipService , messagingService , new DefaultPrimitiveTypeRegistry ( registry . getTypes ( PrimitiveType . class ) ) , buildSystemPartitionGroup ( config ) , partitionGroups , new DefaultPartitionGroupTypeRegistry ( registry . getTypes ( PartitionGroup . Type . class ) ) ) ; } | Builds a partition service . |
20,093 | public static PrimitiveId from ( String id ) { return from ( Hashing . sha256 ( ) . hashString ( id , StandardCharsets . UTF_8 ) . asLong ( ) ) ; } | Creates a snapshot ID from the given string . |
20,094 | public void delete ( ) { LOGGER . debug ( "Deleting {}" , this ) ; Path path = file . file ( ) . toPath ( ) ; if ( Files . exists ( path ) ) { try { Files . delete ( file . file ( ) . toPath ( ) ) ; } catch ( IOException e ) { } } } | Deletes the snapshot file . |
20,095 | public AtomixConfig setPartitionGroups ( Map < String , PartitionGroupConfig < ? > > partitionGroups ) { partitionGroups . forEach ( ( name , group ) -> group . setName ( name ) ) ; this . partitionGroups = partitionGroups ; return this ; } | Sets the partition group configurations . |
20,096 | @ SuppressWarnings ( "unchecked" ) public < C extends PrimitiveConfig < C > > C getPrimitiveDefault ( String name ) { return ( C ) primitiveDefaults . get ( name ) ; } | Returns a default primitive configuration . |
20,097 | public AtomixConfig addPrimitive ( String name , PrimitiveConfig config ) { primitives . put ( name , config ) ; return this ; } | Adds a primitive configuration . |
20,098 | @ SuppressWarnings ( "unchecked" ) public < C extends PrimitiveConfig < C > > C getPrimitive ( String name ) { return ( C ) primitives . get ( name ) ; } | Returns a primitive configuration . |
20,099 | private boolean isRunningOutOfDiskSpace ( ) { return raft . getStorage ( ) . statistics ( ) . getUsableSpace ( ) < raft . getStorage ( ) . maxLogSegmentSize ( ) * SEGMENT_BUFFER_FACTOR || raft . getStorage ( ) . statistics ( ) . getUsableSpace ( ) / ( double ) raft . getStorage ( ) . statistics ( ) . getTotalSpace ( ) < raft . getStorage ( ) . freeDiskBuffer ( ) ; } | Returns a boolean indicating whether the node is running out of disk space . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.