idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
23,000
synchronized void refresh ( RollingSegmentHandle source ) { Preconditions . checkArgument ( source . getSegmentName ( ) . equals ( this . getSegmentName ( ) ) , "SegmentName mismatch." ) ; if ( this . readOnly == source . readOnly ) { this . headerHandle = source . headerHandle ; } this . segmentChunks = new ArrayList ...
Updates the contents of this handle with information from the given one .
23,001
synchronized void markSealed ( ) { if ( ! this . sealed ) { this . sealed = true ; this . segmentChunks = Collections . unmodifiableList ( this . segmentChunks ) ; this . activeChunkHandle = null ; } }
Records the fact that the Segment represented by this Handle has been sealed .
23,002
synchronized void addChunk ( SegmentChunk segmentChunk , SegmentHandle activeChunkHandle ) { Preconditions . checkState ( ! this . sealed , "Cannot add SegmentChunks for a Sealed Handle." ) ; if ( this . segmentChunks . size ( ) > 0 ) { long expectedOffset = this . segmentChunks . get ( this . segmentChunks . size ( ) ...
Adds a new SegmentChunk .
23,003
synchronized void addChunks ( List < SegmentChunk > segmentChunks ) { Preconditions . checkState ( ! this . sealed , "Cannot add SegmentChunks for a Sealed Handle." ) ; long expectedOffset = 0 ; if ( this . segmentChunks . size ( ) > 0 ) { expectedOffset = this . segmentChunks . get ( this . segmentChunks . size ( ) - ...
Adds multiple SegmentChunks .
23,004
synchronized void setActiveChunkHandle ( SegmentHandle handle ) { Preconditions . checkArgument ( handle == null || ! handle . isReadOnly ( ) , "Active SegmentChunk handle cannot be readonly." ) ; SegmentChunk last = lastChunk ( ) ; Preconditions . checkState ( last != null , "Cannot set an Active SegmentChunk handle w...
Sets the Active SegmentChunk handle .
23,005
< T > CompletableFuture < T > executeIfEmpty ( DirectSegmentAccess segment , Supplier < CompletableFuture < T > > action , TimeoutTimer timer ) { return this . recoveryTracker . waitIfNeeded ( segment , ( ) -> this . conditionalUpdateProcessor . addWithFilter ( conditionKey -> conditionKey . getKey ( ) == segment . get...
Executes the given action only if the Segment is empty .
23,006
CompletableFuture < Map < UUID , Long > > getBucketOffsets ( DirectSegmentAccess segment , Collection < UUID > hashes , TimeoutTimer timer ) { Exceptions . checkNotClosed ( this . closed . get ( ) , this ) ; if ( hashes . isEmpty ( ) ) { return CompletableFuture . completedFuture ( Collections . emptyMap ( ) ) ; } val ...
Finds the Last Bucket Offsets for the given KeyHashes .
23,007
CompletableFuture < List < Long > > update ( DirectSegmentAccess segment , TableKeyBatch batch , Supplier < CompletableFuture < Long > > persist , TimeoutTimer timer ) { Exceptions . checkNotClosed ( this . closed . get ( ) , this ) ; if ( batch . isConditional ( ) ) { val keys = batch . getVersionedItems ( ) . stream ...
Performs a Batch Update or Removal .
23,008
private CompletableFuture < Void > validateConditionalUpdate ( DirectSegmentAccess segment , TableKeyBatch batch , TimeoutTimer timer ) { Exceptions . checkNotClosed ( this . closed . get ( ) , this ) ; List < UUID > hashes = batch . getVersionedItems ( ) . stream ( ) . map ( TableKeyBatch . Item :: getHash ) . collect...
Validates all the conditional updates specified in the given TableKeyBatch .
23,009
@ SneakyThrows ( ConditionalTableUpdateException . class ) private void validateConditionalUpdate ( List < TableKeyBatch . Item > items , Map < UUID , Long > bucketOffsets , String segmentName ) { val badKeyVersions = new HashMap < TableKey , Long > ( ) ; for ( val item : items ) { TableKey key = item . getKey ( ) ; Lo...
Validates a list of UpdateBatchItems against their actual Table Bucket offsets .
23,010
< T extends WriterSegmentProcessor > long getHighestCommittedSequenceNumber ( Iterable < T > processors ) { long lowestUncommittedSeqNo = Long . MAX_VALUE ; for ( WriterSegmentProcessor a : processors ) { if ( ! a . isClosed ( ) ) { long firstSeqNo = a . getLowestUncommittedSequenceNumber ( ) ; if ( firstSeqNo >= 0 ) {...
Determines the largest Sequence Number that can be safely truncated from the Writer s Data Source . All operations up to and including the one for this Sequence Number have been successfully committed to External Storage .
23,011
private void checkAssignment ( ) { long traceId = LoggerHelpers . traceEnter ( log , "checkAssignment" ) ; try { Exceptions . checkNotClosed ( closed . get ( ) , this ) ; Set < Integer > desiredList = getDesiredContainerList ( ) ; if ( desiredList != null ) { Collection < Integer > runningContainers = new HashSet < > (...
The container assignment monitor . This method will fetch the current owned containers for this host and ensures that the local containers state reflects this .
23,012
private CompletableFuture < Void > stopContainer ( int containerId ) { log . info ( "Stopping Container {}." , containerId ) ; ContainerHandle handle = handles . get ( containerId ) ; if ( handle == null ) { log . warn ( "Container {} handle is null, container is pending start or already unregistered." , containerId ) ...
Stop the container given its id .
23,013
public static < T > Property < T > named ( String name , T defaultValue ) { return new Property < > ( name , defaultValue ) ; }
Creates a new instance of the Property class with the given default value .
23,014
public void start ( ) throws Exception { if ( isInProcZK ) { zkUrl = "localhost:" + zkPort ; startLocalZK ( ) ; } else { URI zkUri = new URI ( "temp://" + zkUrl ) ; zkHost = zkUri . getHost ( ) ; zkPort = zkUri . getPort ( ) ; } if ( isInProcHDFS ) { startLocalHDFS ( ) ; hdfsUrl = String . format ( "hdfs://localhost:%d...
Kicks off the cluster creation . right now it can be done only once in lifetime of a process .
23,015
private void startLocalSegmentStore ( int segmentStoreId ) throws Exception { Properties authProps = new Properties ( ) ; authProps . setProperty ( "pravega.client.auth.method" , "Default" ) ; authProps . setProperty ( "pravega.client.auth.userName" , "arvind" ) ; authProps . setProperty ( "pravega.client.auth.password...
Starts a SegmentStore with the given id . This is re - entrant . Eventually this will allow starting and stopping of individual SegmentStore instances . This is not possible right now .
23,016
int commit ( long upToTransactionId ) { long traceId = LoggerHelpers . traceEnterWithContext ( log , this . traceObjectId , "commit" , upToTransactionId ) ; List < Long > commits = new ArrayList < > ( ) ; while ( ! this . transactions . isEmpty ( ) && this . transactions . peekFirst ( ) . getTransactionId ( ) <= upToTr...
Commits all outstanding changes to the base Container Metadata up to and including the one for the given UpdateTransaction .
23,017
void rollback ( long fromTransactionId ) { long traceId = LoggerHelpers . traceEnterWithContext ( log , this . traceObjectId , "rollback" , fromTransactionId ) ; List < Long > rolledBack = new ArrayList < > ( ) ; while ( ! this . transactions . isEmpty ( ) && this . transactions . peekLast ( ) . getTransactionId ( ) >=...
Discards any outstanding changes starting at the given UpdateTransaction forward .
23,018
public CompletableFuture < Void > process ( Operation operation ) { CompletableFuture < Void > result = new CompletableFuture < > ( ) ; if ( ! isRunning ( ) ) { result . completeExceptionally ( new IllegalContainerStateException ( "OperationProcessor is not running." ) ) ; } else { log . debug ( "{}: process {}." , thi...
Processes the given Operation . This method returns when the given Operation has been added to the internal queue .
23,019
private CompletableFuture < Void > throttle ( ) { val delay = new AtomicReference < ThrottlerCalculator . DelayResult > ( this . throttlerCalculator . getThrottlingDelay ( ) ) ; if ( ! delay . get ( ) . isMaximum ( ) ) { return throttleOnce ( delay . get ( ) . getDurationMillis ( ) , delay . get ( ) . isMaximum ( ) ) ;...
region Queue Processing
23,020
private void closeQueue ( Throwable causingException ) { Collection < CompletableOperation > remainingOperations = this . operationQueue . close ( ) ; if ( remainingOperations != null && remainingOperations . size ( ) > 0 ) { Throwable failException = causingException != null ? causingException : new CancellationExcept...
Closes the Operation Queue and fails all Operations in it with the given exception .
23,021
private void cancelIncompleteOperations ( Iterable < CompletableOperation > operations , Throwable failException ) { assert failException != null : "no exception to set" ; int cancelCount = 0 ; for ( CompletableOperation o : operations ) { if ( ! o . isDone ( ) ) { this . state . failOperation ( o , failException ) ; c...
Cancels those Operations in the given list that have not yet completed with the given exception .
23,022
protected CuratorFramework createZKClient ( ) { val serviceConfig = getServiceConfig ( ) ; CuratorFramework zkClient = CuratorFrameworkFactory . builder ( ) . connectString ( serviceConfig . getZkURL ( ) ) . namespace ( "pravega/" + serviceConfig . getClusterName ( ) ) . retryPolicy ( new ExponentialBackoffRetry ( serv...
Creates a new instance of the CuratorFramework class using configuration from the shared AdminCommandState .
23,023
public void takeLeadership ( CuratorFramework client ) throws Exception { log . info ( "Obtained leadership to monitor the Host to Segment Container Mapping" ) ; hostsChange . release ( ) ; pravegaServiceCluster = new ClusterZKImpl ( client , ClusterType . HOST ) ; pravegaServiceCluster . addListener ( ( type , host ) ...
This function is called when the current instance is made the leader . The leadership is relinquished when this function exits .
23,024
private void performNextWrite ( ) { Append append = getNextAppend ( ) ; if ( append == null ) { return ; } long traceId = LoggerHelpers . traceEnter ( log , "storeAppend" , append ) ; Timer timer = new Timer ( ) ; storeAppend ( append ) . whenComplete ( ( v , e ) -> { handleAppendResult ( append , e , timer ) ; LoggerH...
If there isn t already an append outstanding against the store write a new one . Appends are opportunistically batched here . i . e . If many are waiting they are combined into a single append and that is written .
23,025
private void pauseOrResumeReading ( ) { int bytesWaiting ; synchronized ( lock ) { bytesWaiting = waitingAppends . values ( ) . stream ( ) . mapToInt ( a -> a . getData ( ) . readableBytes ( ) ) . sum ( ) ; } if ( bytesWaiting > HIGH_WATER_MARK ) { log . debug ( "Pausing writing from connection {}" , connection ) ; con...
If there is too much data waiting throttle the producer by stopping consumption from the socket . If there is room for more data we resume consuming from the socket .
23,026
public void append ( Append append ) { log . trace ( "Processing append received from client {}" , append ) ; UUID id = append . getWriterId ( ) ; synchronized ( lock ) { Long lastEventNumber = latestEventNumbers . get ( Pair . of ( append . getSegment ( ) , id ) ) ; Preconditions . checkState ( lastEventNumber != null...
Append data to the store . Because ordering dictates that there only be one outstanding append from a given connection this is implemented by adding the append to a queue .
23,027
public String get ( Property < String > property ) throws ConfigurationException { return tryGet ( property , s -> s ) ; }
Gets the value of a String property .
23,028
public < T extends Enum < T > > T getEnum ( Property < T > property , Class < T > enumClass ) throws ConfigurationException { return tryGet ( property , s -> Enum . valueOf ( enumClass , s ) ) ; }
Gets the value of an Enumeration property .
23,029
public ClientConnection createFlow ( final Flow flow , final ReplyProcessor rp ) { Exceptions . checkNotClosed ( closed . get ( ) , this ) ; Preconditions . checkState ( ! disableFlow . get ( ) , "Ensure flows are enabled." ) ; log . info ( "Creating Flow {} for endpoint {}. The current Channel is {}." , flow . getFlow...
Create a flow on existing connection .
23,030
public void closeFlow ( ClientConnection clientConnection ) { final ClientConnectionImpl clientConnectionImpl = ( ClientConnectionImpl ) clientConnection ; int flow = clientConnectionImpl . getFlowId ( ) ; log . info ( "Closing Flow {} for endpoint {}" , flow , clientConnectionImpl . getConnectionName ( ) ) ; flowIdRep...
Close a flow . This is invoked when the ClientConnection is closed .
23,031
void completeWhenRegistered ( final CompletableFuture < Void > future ) { Preconditions . checkNotNull ( future , "future" ) ; registeredFutureLatch . register ( future ) ; }
This function completes the input future when the channel is registered .
23,032
synchronized PageWrapper getRootPage ( ) { return this . pageByOffset . values ( ) . stream ( ) . filter ( page -> page . getParent ( ) == null ) . findFirst ( ) . orElse ( null ) ; }
Gets a pointer to the Root Page .
23,033
void initializeReader ( long initialAllocationDelay ) { boolean alreadyAdded = sync . updateState ( ( state , updates ) -> { if ( state . getSegments ( readerId ) == null ) { log . debug ( "Adding reader {} to reader grop. CurrentState is: {}" , readerId , state ) ; updates . add ( new AddReader ( readerId ) ) ; return...
Add this reader to the reader group so that it is able to acquire segments
23,034
static void readerShutdown ( String readerId , Position lastPosition , StateSynchronizer < ReaderGroupState > sync ) { sync . updateState ( ( state , updates ) -> { Set < Segment > segments = state . getSegments ( readerId ) ; if ( segments == null ) { return ; } log . debug ( "Removing reader {} from reader grop. Curr...
Shuts down a reader releasing all of its segments . The reader should cease all operations .
23,035
boolean handleEndOfSegment ( Segment segmentCompleted ) throws ReaderNotInReaderGroupException { final Map < Segment , List < Long > > segmentToPredecessor ; if ( sync . getState ( ) . getEndSegments ( ) . containsKey ( segmentCompleted ) ) { segmentToPredecessor = Collections . emptyMap ( ) ; } else { val successors =...
Handles a segment being completed by calling the controller to gather all successors to the completed segment . To ensure consistent checkpoints a segment cannot be released while a checkpoint for the reader is pending so it may or may not succeed .
23,036
Segment findSegmentToReleaseIfRequired ( ) { fetchUpdatesIfNeeded ( ) ; Segment segment = null ; synchronized ( decisionLock ) { if ( ! releaseTimer . hasRemaining ( ) && sync . getState ( ) . getCheckpointForReader ( readerId ) == null && doesReaderOwnTooManySegments ( sync . getState ( ) ) ) { segment = findSegmentTo...
If a segment should be released because the distribution of segments is imbalanced and this reader has not done so in a while this returns the segment that should be released .
23,037
private boolean doesReaderOwnTooManySegments ( ReaderGroupState state ) { Map < String , Double > sizesOfAssignemnts = state . getRelativeSizes ( ) ; Set < Segment > assignedSegments = state . getSegments ( readerId ) ; if ( sizesOfAssignemnts . isEmpty ( ) || assignedSegments == null || assignedSegments . size ( ) <= ...
Returns true if this reader owns multiple segments and has more than a full segment more than the reader with the least assigned to it .
23,038
private Segment findSegmentToRelease ( ) { Set < Segment > segments = sync . getState ( ) . getSegments ( readerId ) ; return segments . stream ( ) . max ( ( s1 , s2 ) -> Double . compare ( hashHelper . hashToRange ( s1 . getScopedName ( ) ) , hashHelper . hashToRange ( s2 . getScopedName ( ) ) ) ) . orElse ( null ) ; ...
Given a set of segments returns one to release . The one returned is arbitrary .
23,039
long getEndOffsetForSegment ( Segment segment ) { return Optional . ofNullable ( sync . getState ( ) . getEndSegments ( ) . get ( segment ) ) . orElse ( Long . MAX_VALUE ) ; }
Fetch the configured end offset for a configured segment . If end offset is not configured return Long . MAX_VALUE .
23,040
boolean releaseSegment ( Segment segment , long lastOffset , long timeLag ) throws ReaderNotInReaderGroupException { sync . updateState ( ( state , updates ) -> { Set < Segment > segments = state . getSegments ( readerId ) ; if ( segments != null && segments . contains ( segment ) && state . getCheckpointForReader ( re...
Releases a segment to another reader . This reader should no longer read from the segment .
23,041
Map < Segment , Long > acquireNewSegmentsIfNeeded ( long timeLag ) throws ReaderNotInReaderGroupException { fetchUpdatesIfNeeded ( ) ; if ( shouldAcquireSegment ( ) ) { return acquireSegment ( timeLag ) ; } else { return Collections . emptyMap ( ) ; } }
If there are unassigned segments and this host has not acquired one in a while acquires them .
23,042
public static CompletableFuture < Void > startAsync ( Service service , Executor executor ) { Preconditions . checkState ( service . state ( ) == Service . State . NEW , "Service expected to be %s but was %s." , Service . State . NEW , service . state ( ) ) ; Preconditions . checkNotNull ( executor , "executor" ) ; Com...
Asynchronously starts a Service and returns a CompletableFuture that will indicate when it is running .
23,043
public static CompletableFuture < Void > stopAsync ( Service service , Executor executor ) { CompletableFuture < Void > result = new CompletableFuture < > ( ) ; onStop ( service , ( ) -> result . complete ( null ) , result :: completeExceptionally , executor ) ; service . stopAsync ( ) ; return result ; }
Asynchronously stops a Service and returns a CompletableFuture that will indicate when it is stopped .
23,044
public static void onStop ( Service service , Runnable terminatedCallback , Consumer < Throwable > failureCallback , Executor executor ) { ShutdownListener listener = new ShutdownListener ( terminatedCallback , failureCallback ) ; service . addListener ( listener , executor ) ; Service . State state = service . state (...
Attaches the given callbacks which will be invoked when the given Service enters a TERMINATED or FAILED state . The callbacks are optional and may be invoked synchronously if the Service is already in one of these states .
23,045
public static boolean isTerminating ( Service . State state ) { return state == Service . State . STOPPING || state == Service . State . TERMINATED || state == Service . State . FAILED ; }
Determines whether the given Service . State indicates the Service is either in the process of Stopping or already Terminated or Failed .
23,046
public void createTransaction ( String scope , String streamName , Duration latency ) { DYNAMIC_LOGGER . incCounterValue ( globalMetricName ( CREATE_TRANSACTION ) , 1 ) ; DYNAMIC_LOGGER . incCounterValue ( CREATE_TRANSACTION , 1 , streamTags ( scope , streamName ) ) ; createTransactionLatency . reportSuccessValue ( lat...
This method increments the global and Stream - related counters of created Transactions and reports the latency of the operation .
23,047
public void createTransactionFailed ( String scope , String streamName ) { DYNAMIC_LOGGER . incCounterValue ( globalMetricName ( CREATE_TRANSACTION_FAILED ) , 1 ) ; DYNAMIC_LOGGER . incCounterValue ( CREATE_TRANSACTION_FAILED , 1 , streamTags ( scope , streamName ) ) ; }
This method increments the global and Stream - related counters of failed Transaction create operations .
23,048
public void commitTransaction ( String scope , String streamName , Duration latency ) { DYNAMIC_LOGGER . incCounterValue ( globalMetricName ( COMMIT_TRANSACTION ) , 1 ) ; DYNAMIC_LOGGER . incCounterValue ( COMMIT_TRANSACTION , 1 , streamTags ( scope , streamName ) ) ; commitTransactionLatency . reportSuccessValue ( lat...
This method increments the global and Stream - related counters of committed Transactions and reports the latency of the operation .
23,049
public void commitTransactionFailed ( String scope , String streamName , String txnId ) { DYNAMIC_LOGGER . incCounterValue ( globalMetricName ( COMMIT_TRANSACTION_FAILED ) , 1 ) ; DYNAMIC_LOGGER . incCounterValue ( COMMIT_TRANSACTION_FAILED , 1 , streamTags ( scope , streamName ) ) ; DYNAMIC_LOGGER . incCounterValue ( ...
This method increments the global Stream - related and Transaction - related counters of failed commit operations .
23,050
public void abortTransaction ( String scope , String streamName , Duration latency ) { DYNAMIC_LOGGER . incCounterValue ( globalMetricName ( ABORT_TRANSACTION ) , 1 ) ; DYNAMIC_LOGGER . incCounterValue ( ABORT_TRANSACTION , 1 , streamTags ( scope , streamName ) ) ; abortTransactionLatency . reportSuccessValue ( latency...
This method increments the global and Stream - related counters of aborted Transactions and reports the latency of the operation .
23,051
public void abortTransactionFailed ( String scope , String streamName , String txnId ) { DYNAMIC_LOGGER . incCounterValue ( globalMetricName ( ABORT_TRANSACTION_FAILED ) , 1 ) ; DYNAMIC_LOGGER . incCounterValue ( ABORT_TRANSACTION_FAILED , 1 , streamTags ( scope , streamName ) ) ; DYNAMIC_LOGGER . incCounterValue ( ABO...
This method increments the global Stream - related and Transaction - related counters of failed abort operations .
23,052
public static void reportOpenTransactions ( String scope , String streamName , int ongoingTransactions ) { DYNAMIC_LOGGER . reportGaugeValue ( OPEN_TRANSACTIONS , ongoingTransactions , streamTags ( scope , streamName ) ) ; }
This method reports the current number of open Transactions for a Stream .
23,053
public Principal authenticate ( List < String > authHeader ) throws AuthException { if ( isAuthEnabled ( ) ) { String credentials = parseCredentials ( authHeader ) ; return pravegaAuthManager . authenticate ( credentials ) ; } return null ; }
Authenticates the subject represented by the specified HTTP Authorization Header value .
23,054
public int getNumberOfSegments ( ) { return assignedSegments . values ( ) . stream ( ) . mapToInt ( Map :: size ) . sum ( ) + unassignedSegments . size ( ) ; }
Returns the number of segments currently being read from and that are unassigned within the reader group .
23,055
public boolean isEndOfData ( ) { return futureSegments . isEmpty ( ) && unassignedSegments . isEmpty ( ) && assignedSegments . values ( ) . stream ( ) . allMatch ( Map :: isEmpty ) ; }
This functions returns true if the readers part of reader group for sealed streams have completely read the data .
23,056
protected void executionComplete ( Throwable exception ) { Collection < QueueItem > toFail = null ; Throwable failEx = null ; synchronized ( this . stateLock ) { this . activeCount -- ; if ( exception != null && ! this . closed ) { failEx = new ProcessingException ( "A previous item failed to commit. Cannot process new...
Callback that is invoked when an item has completed execution .
23,057
protected < T > CompletableFuture < T > invoke ( String streamSegmentName , Function < SegmentContainer , CompletableFuture < T > > toInvoke , String methodName , Object ... logArgs ) { long traceId = LoggerHelpers . traceEnter ( log , methodName , logArgs ) ; SegmentContainer container ; try { int containerId = this ....
Executes the given Function on the SegmentContainer that the given Segment maps to .
23,058
CompletableFuture < Void > createSegment ( String segmentName , Collection < AttributeUpdate > attributes , Duration timeout ) { long traceId = LoggerHelpers . traceEnterWithContext ( log , traceObjectId , "createSegment" , segmentName ) ; long segmentId = this . connector . containerMetadata . getStreamSegmentId ( seg...
Creates a new Segment with given name .
23,059
CompletableFuture < SegmentProperties > getSegmentInfo ( String segmentName , Duration timeout ) { long streamSegmentId = this . connector . containerMetadata . getStreamSegmentId ( segmentName , true ) ; CompletableFuture < SegmentProperties > result ; if ( isValidSegmentId ( streamSegmentId ) ) { SegmentMetadata sm =...
Gets information about a Segment . If the Segment is active it returns this information directly from the in - memory Metadata . If the Segment is not active it fetches the information from Storage and returns it without activating the segment in the Metadata or otherwise touching the DurableLog .
23,060
CompletableFuture < Void > updateSegmentInfo ( SegmentMetadata segmentMetadata , Duration timeout ) { if ( segmentMetadata . isMerged ( ) ) { return Futures . failedFuture ( new StreamSegmentMergedException ( segmentMetadata . getName ( ) ) ) ; } else if ( segmentMetadata . isDeleted ( ) ) { return Futures . failedFutu...
Updates information about a Segment .
23,061
private void assignSegmentId ( String segmentName , Duration timeout ) { TimeoutTimer timer = new TimeoutTimer ( timeout ) ; Futures . exceptionListener ( getSegmentInfoInternal ( segmentName , timer . getRemaining ( ) ) . thenComposeAsync ( si -> submitAssignmentWithRetry ( SegmentInfo . deserialize ( si ) , timer . g...
Attempts to map a Segment to an Id by first trying to retrieve an existing id and should that not exist assign a new one .
23,062
private CompletableFuture < Long > submitAssignmentWithRetry ( SegmentInfo segmentInfo , Duration timeout ) { return retryWithCleanup ( ( ) -> submitAssignment ( segmentInfo , false , timeout ) ) ; }
Same as submitAssignment but retries exactly once in case TooManyActiveSegmentsException was encountered in which case it forces a metadata cleanup before retrying . If the second attempt also fails there will be no more retry and the Exception from the second failure will be the one that this call fails with too .
23,063
private long completeAssignment ( String streamSegmentName , long streamSegmentId ) { assert streamSegmentId != ContainerMetadata . NO_STREAM_SEGMENT_ID : "no valid streamSegmentId given" ; finishPendingRequests ( streamSegmentName , PendingRequest :: complete , streamSegmentId ) ; return streamSegmentId ; }
Completes the assignment for the given StreamSegmentName by completing the waiting CompletableFuture .
23,064
private void failAssignment ( String streamSegmentName , Throwable reason ) { finishPendingRequests ( streamSegmentName , PendingRequest :: completeExceptionally , reason ) ; }
Fails the assignment for the given StreamSegment Id with the given reason .
23,065
private < T > QueuedCallback < T > checkConcurrentAssignment ( String segmentName , Function < Long , CompletableFuture < T > > thenCompose ) { QueuedCallback < T > queuedCallback = null ; synchronized ( this . pendingRequests ) { PendingRequest pendingRequest = this . pendingRequests . getOrDefault ( segmentName , nul...
Attempts to piggyback a task on any existing concurrent assignment if any such assignment exists .
23,066
private < T > CompletableFuture < T > retryWithCleanup ( Supplier < CompletableFuture < T > > toTry ) { CompletableFuture < T > result = new CompletableFuture < > ( ) ; toTry . get ( ) . thenAccept ( result :: complete ) . exceptionally ( ex -> { try { if ( Exceptions . unwrap ( ex ) instanceof TooManyActiveSegmentsExc...
Retries Future from the given supplier exactly once if encountering TooManyActiveSegmentsException .
23,067
public void createScope ( final CreateScopeRequest createScopeRequest , final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "createScope" ) ; try { NameUtils . validateUserScopeName ( createScopeRequest . getScopeName ( ) ) ; } catch ( IllegalA...
Implementation of createScope REST API .
23,068
public void deleteScope ( final String scopeName , final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "deleteScope" ) ; try { restAuthHelper . authenticateAuthorize ( getAuthorizationHeader ( ) , AuthResourceRepresentation . ofScopes ( ) , REA...
Implementation of deleteScope REST API .
23,069
public void deleteStream ( final String scopeName , final String streamName , final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "deleteStream" ) ; try { restAuthHelper . authenticateAuthorize ( getAuthorizationHeader ( ) , AuthResourceReprese...
Implementation of deleteStream REST API .
23,070
public void getScope ( final String scopeName , final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "getScope" ) ; try { restAuthHelper . authenticateAuthorize ( getAuthorizationHeader ( ) , AuthResourceRepresentation . ofScope ( scopeName ) , ...
Implementation of getScope REST API .
23,071
public void listScopes ( final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "listScopes" ) ; final Principal principal ; final List < String > authHeader = getAuthorizationHeader ( ) ; try { principal = restAuthHelper . authenticate ( authHead...
Implementation of listScopes REST API .
23,072
public void listStreams ( final String scopeName , final String showInternalStreams , final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "listStreams" ) ; final Principal principal ; final List < String > authHeader = getAuthorizationHeader ( ...
Implementation of listStreams REST API .
23,073
public void updateStream ( final String scopeName , final String streamName , final UpdateStreamRequest updateStreamRequest , final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "updateStream" ) ; try { restAuthHelper . authenticateAuthorize ( ...
Implementation of updateStream REST API .
23,074
public void updateStreamState ( final String scopeName , final String streamName , final StreamState updateStreamStateRequest , SecurityContext securityContext , AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "updateStreamState" ) ; try { restAuthHelper . authenticateAuthorize ( getAu...
Implementation of updateStreamState REST API .
23,075
public void getScalingEvents ( final String scopeName , final String streamName , final Long from , final Long to , final SecurityContext securityContext , final AsyncResponse asyncResponse ) { long traceId = LoggerHelpers . traceEnter ( log , "getScalingEvents" ) ; try { restAuthHelper . authenticateAuthorize ( getAut...
Implementation of getScalingEvents REST API .
23,076
private void initialize ( ByteArraySegment footer , long footerOffset , long indexLength ) { if ( footer . getLength ( ) != FOOTER_LENGTH ) { throw new IllegalDataFormatException ( String . format ( "Wrong footer length. Expected %s, actual %s." , FOOTER_LENGTH , footer . getLength ( ) ) ) ; } long rootPageOffset = get...
Initializes the BTreeIndex using information from the given footer .
23,077
private CompletableFuture < UpdateablePageCollection > applyUpdates ( Iterator < PageEntry > updates , TimeoutTimer timer ) { UpdateablePageCollection pageCollection = new UpdateablePageCollection ( this . state . get ( ) . length ) ; AtomicReference < PageWrapper > lastPage = new AtomicReference < > ( null ) ; val las...
Executes the given updates on the index . Loads up any necessary BTreePage instances in memory but does not persist the changes to the external data source nor does it reassign offsets to the modified pages perform splits etc .
23,078
private CompletableFuture < ? > loadSmallestOffsetPage ( PageCollection pageCollection , TimeoutTimer timer ) { if ( pageCollection . getCount ( ) <= 1 ) { return CompletableFuture . completedFuture ( null ) ; } long minOffset = calculateMinOffset ( pageCollection . getRootPage ( ) ) ; return locatePage ( page -> getPa...
Loads the BTreePage with the smallest offset from the DataSource . The purpose of this is for incremental compaction . The page with the smallest offset will be moved to the end of the index which allows the external data source to perform any truncation necessary in order to free up space .
23,079
private void processSplitPage ( List < BTreePage > splitResult , PageModificationContext context ) { PageWrapper originalPage = context . getPageWrapper ( ) ; for ( int i = 0 ; i < splitResult . size ( ) ; i ++ ) { val page = splitResult . get ( i ) ; ByteArraySegment newPageKey ; long newOffset ; long minOffset ; Page...
Processes a Page Split result . The first split page will replace the existing page while the remaining pages will need to be inserted as children into the parent .
23,080
private long calculateMinOffset ( PageWrapper pageWrapper ) { long min = pageWrapper . getOffset ( ) ; if ( ! pageWrapper . isIndexPage ( ) ) { return min ; } BTreePage page = pageWrapper . getPage ( ) ; int count = page . getCount ( ) ; for ( int pos = 0 ; pos < count ; pos ++ ) { long ppMinOffset = deserializePointer...
Calculates the Minimum Page Offset for this PageWrapper . The Minimum Page Offset is the smallest of this PageWrapper s offset and the MinOffsets of all this PageWrapper s direct children .
23,081
private CompletableFuture < PageWrapper > locatePage ( ByteArraySegment key , PageCollection pageCollection , TimeoutTimer timer ) { Preconditions . checkArgument ( key . getLength ( ) == this . leafPageConfig . getKeyLength ( ) , "Invalid key length." ) ; Preconditions . checkArgument ( pageCollection . getIndexLength...
Locates the Leaf Page that contains or should contain the given Key .
23,082
private CompletableFuture < PageWrapper > locatePage ( Function < BTreePage , PagePointer > getChildPointer , Predicate < PageWrapper > found , PageCollection pageCollection , TimeoutTimer timer ) { AtomicReference < PagePointer > pagePointer = new AtomicReference < > ( new PagePointer ( null , this . state . get ( ) ....
Locates the BTreePage according to the given criteria .
23,083
private CompletableFuture < PageWrapper > fetchPage ( PagePointer pagePointer , PageWrapper parentPage , PageCollection pageCollection , Duration timeout ) { PageWrapper fromCache = pageCollection . get ( pagePointer . getOffset ( ) ) ; if ( fromCache != null ) { return CompletableFuture . completedFuture ( fromCache )...
Loads up a single Page .
23,084
private CompletableFuture < ByteArraySegment > readPage ( long offset , int length , Duration timeout ) { return this . read . apply ( offset , length , timeout ) ; }
Reads the contents of a single page from the external data source .
23,085
private CompletableFuture < Long > writePages ( UpdateablePageCollection pageCollection , Duration timeout ) { IndexState state = this . state . get ( ) ; Preconditions . checkState ( state != null , "Cannot write without fetching the state first." ) ; val pages = new ArrayList < Map . Entry < Long , ByteArraySegment >...
Writes the contents of all the BTreePages in the given PageCollection to the external data source .
23,086
private void formatHeaderAndFooter ( int itemCount , int id ) { this . header . set ( VERSION_OFFSET , CURRENT_VERSION ) ; this . header . set ( FLAGS_OFFSET , getFlags ( this . config . isIndexPage ? FLAG_INDEX_PAGE : FLAG_NONE ) ) ; setHeaderId ( id ) ; setCount ( itemCount ) ; setFooterId ( id ) ; }
Formats the Header and Footer of this BTreePage with the given information .
23,087
ByteArraySegment getValueAt ( int pos ) { Preconditions . checkElementIndex ( pos , getCount ( ) , "pos must be non-negative and smaller than the number of items." ) ; return this . data . subSegment ( pos * this . config . entryLength + this . config . keyLength , this . config . valueLength ) ; }
Gets a ByteArraySegment representing the value at the given Position .
23,088
ByteArraySegment getKeyAt ( int pos ) { Preconditions . checkElementIndex ( pos , getCount ( ) , "pos must be non-negative and smaller than the number of items." ) ; return this . data . subSegment ( pos * this . config . entryLength , this . config . keyLength ) ; }
Gets the Key at the given Position .
23,089
void setFirstKey ( ByteArraySegment newKey ) { Preconditions . checkState ( getCount ( ) > 0 , "BTreePage is empty. Cannot set first key." ) ; Preconditions . checkArgument ( newKey . getLength ( ) == this . config . getKeyLength ( ) , "Incorrect key length." ) ; Preconditions . checkArgument ( KEY_COMPARATOR . compare...
Updates the first PageEntry s key to the given value .
23,090
List < PageEntry > getEntries ( int firstIndex , int lastIndex ) { Preconditions . checkArgument ( firstIndex <= lastIndex , "firstIndex must be smaller than or equal to lastIndex." ) ; ArrayList < PageEntry > result = new ArrayList < > ( ) ; for ( int i = firstIndex ; i <= lastIndex ; i ++ ) { result . add ( getEntryA...
Gets all the Page Entries between the two indices .
23,091
private BTreePage applyInsertsAndRemovals ( ChangeInfo ci ) { int newCount = getCount ( ) + ci . insertCount - ci . deleteCount ; val newPage = new BTreePage ( this . config , new ByteArraySegment ( new byte [ DATA_OFFSET + newCount * this . config . entryLength + FOOTER_LENGTH ] ) , false ) ; newPage . formatHeaderAnd...
Inserts the new PageEntry instances at the given offsets .
23,092
private void setValueAtPosition ( int pos , ByteArraySegment value ) { Preconditions . checkElementIndex ( pos , getCount ( ) , "pos must be non-negative and smaller than the number of items." ) ; Preconditions . checkArgument ( value . getLength ( ) == this . config . valueLength , "Given value has incorrect length." ...
Sets the Value at the given position .
23,093
public CompletableFuture < Void > add ( Operation operation , Duration timeout ) { ensureRunning ( ) ; return this . operationProcessor . process ( operation ) ; }
region OperationLog Implementation
23,094
public void setStreamSegmentId ( long value ) { Preconditions . checkState ( this . streamSegmentId == ContainerMetadata . NO_STREAM_SEGMENT_ID , "StreamSegmentId has already been assigned for this operation." ) ; Preconditions . checkArgument ( value != ContainerMetadata . NO_STREAM_SEGMENT_ID , "Invalid StreamSegment...
Sets the StreamSegmentId for this operation .
23,095
public boolean authenticateAndAuthorize ( String resource , String credentials , AuthHandler . Permissions level ) throws AuthenticationException { Preconditions . checkNotNull ( credentials , "credentials" ) ; boolean retVal = false ; try { String [ ] parts = extractMethodAndToken ( credentials ) ; String method = par...
API to authenticate and authorize access to a given resource .
23,096
public void registerInterceptors ( ServerBuilder < ? > builder ) { try { if ( serverConfig . isAuthorizationEnabled ( ) ) { ServiceLoader < AuthHandler > loader = ServiceLoader . load ( AuthHandler . class ) ; for ( AuthHandler handler : loader ) { try { handler . initialize ( serverConfig ) ; synchronized ( this ) { i...
Loads the custom implementations of the AuthHandler interface dynamically . Registers the interceptors with grpc . Stores the implementation in a local map for routing the REST auth request .
23,097
public double addNewSample ( double newSample ) { final double sample = calculateLog ( newSample ) ; return Double . longBitsToDouble ( valueEncodedAsLong . updateAndGet ( value -> { return Double . doubleToRawLongBits ( sample * newSampleWeight + ( 1.0 - newSampleWeight ) * Double . longBitsToDouble ( value ) ) ; } ) ...
Adds a new sample to the moving average and returns the updated value .
23,098
synchronized QueueStats getStatistics ( ) { int size = this . writes . size ( ) ; double fillRatio = calculateFillRatio ( this . totalLength , size ) ; int processingTime = this . lastDurationMillis ; if ( processingTime == 0 && size > 0 ) { processingTime = ( int ) ( ( this . timeSupplier . get ( ) - this . writes . p...
Gets a snapshot of the queue internals .
23,099
synchronized void add ( Write write ) { Exceptions . checkNotClosed ( this . closed , this ) ; this . writes . addLast ( write ) ; this . totalLength += write . data . getLength ( ) ; write . setQueueAddedTimestamp ( this . timeSupplier . get ( ) ) ; }
Adds a new Write to the end of the queue .