idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
18,900
public static PeriodGranularity toQueryGranularity ( final TimeUnitRange timeUnitRange , final DateTimeZone timeZone ) { final Period period = PERIOD_MAP . get ( timeUnitRange ) ; if ( period == null ) { return null ; } return new PeriodGranularity ( period , null , timeZone ) ; }
Returns the Druid QueryGranularity corresponding to a Calcite TimeUnitRange or null if there is none .
18,901
public static ColumnSelectorFactory makeColumnSelectorFactory ( final VirtualColumns virtualColumns , final AggregatorFactory agg , final Supplier < InputRow > in , final boolean deserializeComplexMetrics ) { final RowBasedColumnSelectorFactory baseSelectorFactory = RowBasedColumnSelectorFactory . create ( in , null ) ...
Column selector used at ingestion time for inputs to aggregators .
18,902
private static void tokenToAuthCookie ( HttpServletResponse resp , String token , String domain , String path , long expires , boolean isCookiePersistent , boolean isSecure ) { resp . addHeader ( "Set-Cookie" , tokenToCookieString ( token , domain , path , expires , isCookiePersistent , isSecure ) ) ; }
Creates the Hadoop authentication HTTP cookie .
18,903
public static Pair < String , String > splitColumnName ( String columnName ) { final int i = columnName . indexOf ( '.' ) ; if ( i < 0 ) { return Pair . of ( columnName , null ) ; } else { return Pair . of ( columnName . substring ( 0 , i ) , columnName . substring ( i + 1 ) ) ; } }
Split a dot - style columnName into the main columnName and the subColumn name after the dot . Useful for columns that support dot notation .
18,904
public ColumnValueSelector < ? > makeColumnValueSelector ( String columnName , ColumnSelectorFactory factory ) { final VirtualColumn virtualColumn = getVirtualColumn ( columnName ) ; if ( virtualColumn == null ) { throw new IAE ( "No such virtual column[%s]" , columnName ) ; } else { final ColumnValueSelector < ? > sel...
Create a column value selector .
18,905
public CacheKeyBuilder appendStrings ( Collection < String > input ) { appendItem ( STRING_LIST_KEY , stringCollectionToByteArray ( input , true ) ) ; return this ; }
Add a collection of strings to the cache key . Strings in the collection are concatenated with a separator of 0xFF and they appear in the cache key in their input order .
18,906
public CacheKeyBuilder appendStringsIgnoringOrder ( Collection < String > input ) { appendItem ( STRING_LIST_KEY , stringCollectionToByteArray ( input , false ) ) ; return this ; }
Add a collection of strings to the cache key . Strings in the collection are sorted by their byte representation and concatenated with a separator of 0xFF .
18,907
public CacheKeyBuilder appendCacheables ( Collection < ? extends Cacheable > input ) { appendItem ( CACHEABLE_LIST_KEY , cacheableCollectionToByteArray ( input , true ) ) ; return this ; }
Add a collection of Cacheables to the cache key . Cacheables in the collection are concatenated without any separator and they appear in the cache key in their input order .
18,908
public CacheKeyBuilder appendCacheablesIgnoringOrder ( Collection < ? extends Cacheable > input ) { appendItem ( CACHEABLE_LIST_KEY , cacheableCollectionToByteArray ( input , false ) ) ; return this ; }
Add a collection of Cacheables to the cache key . Cacheables in the collection are sorted by their byte representation and concatenated without any separator .
18,909
public RelDataType getRelDataType ( final RelDataTypeFactory typeFactory ) { final RelDataTypeFactory . Builder builder = typeFactory . builder ( ) ; for ( final String columnName : columnNames ) { final ValueType columnType = getColumnType ( columnName ) ; final RelDataType type ; if ( ColumnHolder . TIME_COLUMN_NAME ...
Returns a Calcite RelDataType corresponding to this row signature .
18,910
public static String generateUuid ( String ... extraData ) { String extra = null ; if ( extraData != null && extraData . length > 0 ) { final ArrayList < String > extraStrings = new ArrayList < > ( extraData . length ) ; for ( String extraString : extraData ) { if ( ! Strings . isNullOrEmpty ( extraString ) ) { extraSt...
Generates a universally unique identifier .
18,911
public static List < PostAggregator > prepareAggregations ( List < String > otherOutputNames , List < AggregatorFactory > aggFactories , List < PostAggregator > postAggs ) { Preconditions . checkNotNull ( otherOutputNames , "otherOutputNames cannot be null" ) ; Preconditions . checkNotNull ( aggFactories , "aggregation...
Returns decorated post - aggregators based on original un - decorated post - aggregators . In addition this method also verifies that there are no output name collisions and that all of the post - aggregators required input fields are present .
18,912
private long calculateLimit ( ScanQuery query , Map < String , Object > responseContext ) { if ( query . getOrder ( ) . equals ( ScanQuery . Order . NONE ) ) { return query . getLimit ( ) - ( long ) responseContext . get ( ScanQueryRunnerFactory . CTX_COUNT ) ; } return query . getLimit ( ) ; }
If we re performing time - ordering we want to scan through the first limit rows in each segment ignoring the number of rows already counted on other segments .
18,913
public void setValues ( int [ ] values , int size ) { if ( size < 0 || size > values . length ) { throw new IAE ( "Size[%d] should be between 0 and %d" , size , values . length ) ; } ensureSize ( size ) ; System . arraycopy ( values , 0 , expansion , 0 , size ) ; this . size = size ; }
Sets the values from the given array . The given values array is not reused and not prone to be mutated later . Instead the values from this array are copied into an array which is internal to ArrayBasedIndexedInts .
18,914
public static double computeJointSegmentsCost ( final DataSegment segmentA , final DataSegment segmentB ) { final Interval intervalA = segmentA . getInterval ( ) ; final Interval intervalB = segmentB . getInterval ( ) ; final double t0 = intervalA . getStartMillis ( ) ; final double t1 = ( intervalA . getEndMillis ( ) ...
This defines the unnormalized cost function between two segments .
18,915
public static double intervalCost ( double x1 , double y0 , double y1 ) { if ( x1 == 0 || y1 == y0 ) { return 0 ; } if ( y0 < 0 ) { double tmp = x1 ; x1 = y1 - y0 ; y1 = tmp - y0 ; y0 = - y0 ; } if ( y0 < x1 ) { final double beta ; final double gamma ; if ( y1 <= x1 ) { beta = y1 - y0 ; gamma = x1 - y0 ; } else { beta ...
Computes the joint cost of two intervals X = [ x_0 = 0 x_1 ) and Y = [ y_0 y_1 )
18,916
public double calculateInitialTotalCost ( final List < ServerHolder > serverHolders ) { double cost = 0 ; for ( ServerHolder server : serverHolders ) { Iterable < DataSegment > segments = server . getServer ( ) . getLazyAllSegments ( ) ; for ( DataSegment s : segments ) { cost += computeJointSegmentsCost ( s , segments...
Calculates the initial cost of the Druid segment configuration .
18,917
protected Pair < Double , ServerHolder > chooseBestServer ( final DataSegment proposalSegment , final Iterable < ServerHolder > serverHolders , final boolean includeCurrentServer ) { Pair < Double , ServerHolder > bestServer = Pair . of ( Double . POSITIVE_INFINITY , null ) ; List < ListenableFuture < Pair < Double , S...
For assignment we want to move to the lowest cost server that isn t already serving the segment .
18,918
public ConnectionFactory build ( ) { return new DefaultConnectionFactory ( ) { public NodeLocator createLocator ( List < MemcachedNode > nodes ) { switch ( locator ) { case ARRAY_MOD : return new ArrayModNodeLocator ( nodes , getHashAlg ( ) ) ; case CONSISTENT : return new KetamaNodeLocator ( nodes , getHashAlg ( ) , n...
borrowed from ConnectionFactoryBuilder to allow setting number of repetitions for KetamaNodeLocator
18,919
protected Map < String , String > getLagPerPartition ( Map < String , String > currentOffsets ) { return ImmutableMap . of ( ) ; }
not yet supported will be implemented in the future
18,920
private int findMinGrandChild ( Comparator comparator , int index ) { int leftChildIndex = getLeftChildIndex ( index ) ; if ( leftChildIndex < 0 ) { return - 1 ; } return findMin ( comparator , getLeftChildIndex ( leftChildIndex ) , 4 ) ; }
Returns the minimum grand child or - 1 if no grand child exists .
18,921
private int findMaxElementIndex ( ) { switch ( heapSize ) { case 1 : return 0 ; case 2 : return 1 ; default : int offset1 = buf . getInt ( 1 * Integer . BYTES ) ; int offset2 = buf . getInt ( 2 * Integer . BYTES ) ; return maxComparator . compare ( offset1 , offset2 ) <= 0 ? 1 : 2 ; } }
Returns the index of the max element .
18,922
public static void register ( Binder binder , Annotation annotation ) { registerKey ( binder , Key . get ( new TypeLiteral < DruidNode > ( ) { } , annotation ) ) ; }
Requests that the annotated DruidNode instance be injected and published as part of the lifecycle .
18,923
public static void registerKey ( Binder binder , Key < DruidNode > key ) { DruidBinders . discoveryAnnouncementBinder ( binder ) . addBinding ( ) . toInstance ( new KeyHolder < > ( key ) ) ; LifecycleModule . register ( binder , ServiceAnnouncer . class ) ; }
Requests that the keyed DruidNode instance be injected and published as part of the lifecycle .
18,924
public Set < DataSegment > getInsertedSegments ( final String taskid ) { final Set < DataSegment > segments = new HashSet < > ( ) ; for ( final TaskAction action : storage . getAuditLogs ( taskid ) ) { if ( action instanceof SegmentInsertAction ) { segments . addAll ( ( ( SegmentInsertAction ) action ) . getSegments ( ...
Returns all segments created by this task .
18,925
public static List < String > objectToStrings ( final Object inputValue ) { if ( inputValue == null ) { return Collections . emptyList ( ) ; } else if ( inputValue instanceof List ) { return ( ( List < ? > ) inputValue ) . stream ( ) . map ( String :: valueOf ) . collect ( Collectors . toList ( ) ) ; } else if ( inputV...
Convert an object to a list of strings .
18,926
private int computeRequiredBufferNum ( int numChildNodes , int combineDegree ) { final int numChildrenForLastNode = numChildNodes % combineDegree ; final int numCurLevelNodes = numChildNodes / combineDegree + ( numChildrenForLastNode > 1 ? 1 : 0 ) ; final int numChildOfParentNodes = numCurLevelNodes + ( numChildrenForL...
Recursively compute the number of required buffers for a combining tree in a bottom - up manner . Since each node of the combining tree represents a combining task and each combining task requires one buffer the number of required buffers is the number of nodes of the combining tree .
18,927
private Pair < List < CloseableIterator < Entry < KeyType > > > , List < Future > > buildCombineTree ( List < ? extends CloseableIterator < Entry < KeyType > > > childIterators , Supplier < ByteBuffer > bufferSupplier , AggregatorFactory [ ] combiningFactories , int combineDegree , List < String > dictionary ) { final ...
Recursively build a combining tree in a bottom - up manner . Each node of the tree is a task that combines input iterators asynchronously .
18,928
public final T getSpecializedOrDefault ( T defaultInstance ) { T specialized = getSpecialized ( ) ; return specialized != null ? specialized : defaultInstance ; }
Returns an instance of specialized version of query processing algorithm if available defaultInstance otherwise .
18,929
public static float [ ] decode ( final String encodedCoordinate ) { if ( encodedCoordinate == null ) { return null ; } final ImmutableList < String > parts = ImmutableList . copyOf ( SPLITTER . split ( encodedCoordinate ) ) ; final float [ ] coordinate = new float [ parts . size ( ) ] ; for ( int i = 0 ; i < coordinate...
Decodes encodedCoordinate .
18,930
private List < Pair < DataSegment , Boolean > > getDataSegmentsOverlappingInterval ( final String dataSource , final Interval interval ) { return connector . inReadOnlyTransaction ( ( handle , status ) -> handle . createQuery ( StringUtils . format ( "SELECT used, payload FROM %1$s WHERE dataSource = :dataSource AND st...
Gets a list of all datasegments that overlap the provided interval along with thier used status .
18,931
private VersionedIntervalTimeline < String , DataSegment > buildVersionedIntervalTimeline ( final String dataSource , final Collection < Interval > intervals , final Handle handle ) { return VersionedIntervalTimeline . forSegments ( intervals . stream ( ) . flatMap ( interval -> handle . createQuery ( StringUtils . for...
Builds a VersionedIntervalTimeline containing used segments that overlap the intervals passed .
18,932
protected int findBucket ( final boolean allowNewBucket , final int buckets , final ByteBuffer targetTableBuffer , final ByteBuffer keyBuffer , final int keyHash ) { final int startBucket = keyHash % buckets ; int bucket = startBucket ; outer : while ( true ) { final int bucketOffset = bucket * bucketSizeWithHash ; if ...
Finds the bucket into which we should insert a key .
18,933
public LockResult lock ( final TaskLockType lockType , final Task task , final Interval interval ) throws InterruptedException { giant . lockInterruptibly ( ) ; try { LockResult lockResult ; while ( ! ( lockResult = tryLock ( lockType , task , interval ) ) . isOk ( ) ) { if ( lockResult . isRevoked ( ) ) { return lockR...
Acquires a lock on behalf of a task . Blocks until the lock is acquired .
18,934
public LockResult lock ( final TaskLockType lockType , final Task task , final Interval interval , long timeoutMs ) throws InterruptedException { long nanos = TimeUnit . MILLISECONDS . toNanos ( timeoutMs ) ; giant . lockInterruptibly ( ) ; try { LockResult lockResult ; while ( ! ( lockResult = tryLock ( lockType , tas...
Acquires a lock on behalf of a task waiting up to the specified wait time if necessary .
18,935
public LockResult tryLock ( final TaskLockType lockType , final Task task , final Interval interval ) { giant . lock ( ) ; try { if ( ! activeTasks . contains ( task . getId ( ) ) ) { throw new ISE ( "Unable to grant lock to inactive Task [%s]" , task . getId ( ) ) ; } Preconditions . checkArgument ( interval . toDurat...
Attempt to acquire a lock for a task without removing it from the queue . Can safely be called multiple times on the same task until the lock is preempted .
18,936
public < T > T doInCriticalSection ( Task task , List < Interval > intervals , CriticalAction < T > action ) throws Exception { giant . lock ( ) ; try { return action . perform ( isTaskLocksValid ( task , intervals ) ) ; } finally { giant . unlock ( ) ; } }
Perform the given action with a guarantee that the locks of the task are not revoked in the middle of action . This method first checks that all locks for the given task and intervals are valid and perform the right action .
18,937
public List < TaskLock > findLocksForTask ( final Task task ) { giant . lock ( ) ; try { return Lists . transform ( findLockPossesForTask ( task ) , new Function < TaskLockPosse , TaskLock > ( ) { public TaskLock apply ( TaskLockPosse taskLockPosse ) { return taskLockPosse . getTaskLock ( ) ; } } ) ; } finally { giant ...
Return the currently - active locks for some task .
18,938
public void unlock ( final Task task , final Interval interval ) { giant . lock ( ) ; try { final String dataSource = task . getDataSource ( ) ; final NavigableMap < DateTime , SortedMap < Interval , List < TaskLockPosse > > > dsRunning = running . get ( task . getDataSource ( ) ) ; if ( dsRunning == null || dsRunning ...
Release lock held for a task on a particular interval . Does nothing if the task does not currently hold the mentioned lock .
18,939
public void remove ( final Task task ) { giant . lock ( ) ; try { try { log . info ( "Removing task[%s] from activeTasks" , task . getId ( ) ) ; for ( final TaskLockPosse taskLockPosse : findLockPossesForTask ( task ) ) { unlock ( task , taskLockPosse . getTaskLock ( ) . getInterval ( ) ) ; } } finally { activeTasks . ...
Release all locks for a task and remove task from set of active tasks . Does nothing if the task is not currently locked or not an active task .
18,940
private List < TaskLockPosse > findLockPossesForTask ( final Task task ) { giant . lock ( ) ; try { final NavigableMap < DateTime , SortedMap < Interval , List < TaskLockPosse > > > dsRunning = running . get ( task . getDataSource ( ) ) ; if ( dsRunning == null ) { return ImmutableList . of ( ) ; } else { return dsRunn...
Return the currently - active lock posses for some task .
18,941
private List < TaskLockPosse > findLockPossesOverlapsInterval ( final String dataSource , final Interval interval ) { giant . lock ( ) ; try { final NavigableMap < DateTime , SortedMap < Interval , List < TaskLockPosse > > > dsRunning = running . get ( dataSource ) ; if ( dsRunning == null ) { return Collections . empt...
Return all locks that overlap some search interval .
18,942
public static < T > T retryCloudFilesOperation ( Task < T > f , final int maxTries ) throws Exception { return RetryUtils . retry ( f , CLOUDFILESRETRY , maxTries ) ; }
Retries CloudFiles operations that fail due to io - related exceptions .
18,943
public RangeSet < String > getDimensionRangeSet ( String dimension ) { if ( field instanceof AndDimFilter ) { List < DimFilter > fields = ( ( AndDimFilter ) field ) . getFields ( ) ; return new OrDimFilter ( Lists . transform ( fields , NotDimFilter :: new ) ) . getDimensionRangeSet ( dimension ) ; } if ( field instanc...
There are some special cases involving null that require special casing for And and Or instead of simply taking the complement
18,944
public FullResponseHolder go ( Request request , HttpResponseHandler < FullResponseHolder , FullResponseHolder > responseHandler ) throws IOException , InterruptedException { Preconditions . checkState ( lifecycleLock . awaitStarted ( 1 , TimeUnit . MILLISECONDS ) ) ; for ( int counter = 0 ; counter < MAX_RETRIES ; cou...
Executes a Request object aimed at the leader . Throws IOException if the leader cannot be located .
18,945
public List < String > mergeAndGetDictionary ( ) { final Set < String > mergedDictionary = new HashSet < > ( ) ; mergedDictionary . addAll ( keySerde . getDictionary ( ) ) ; for ( File dictFile : dictionaryFiles ) { try ( final MappingIterator < String > dictIterator = spillMapper . readValues ( spillMapper . getFactor...
Returns a dictionary of string keys added to this grouper . Note that the dictionary of keySerde is spilled on local storage whenever the inner grouper is spilled . If there are spilled dictionaries this method loads them from disk and returns a merged dictionary .
18,946
public static BoundDimFilter not ( final BoundDimFilter bound ) { if ( bound . getUpper ( ) != null && bound . getLower ( ) != null ) { return null ; } else if ( bound . getUpper ( ) != null ) { return new BoundDimFilter ( bound . getDimension ( ) , bound . getUpper ( ) , null , ! bound . isUpperStrict ( ) , false , nu...
Negates single - ended Bound filters .
18,947
private SegmentIdWithShardSpec getSegment ( final InputRow row , final String sequenceName , final boolean skipSegmentLineageCheck ) throws IOException { synchronized ( segments ) { final DateTime timestamp = row . getTimestamp ( ) ; final SegmentIdWithShardSpec existing = getAppendableSegment ( timestamp , sequenceNam...
Return a segment usable for timestamp . May return null if no segment can be allocated .
18,948
ListenableFuture < SegmentsAndMetadata > pushInBackground ( final WrappedCommitter wrappedCommitter , final Collection < SegmentIdWithShardSpec > segmentIdentifiers , final boolean useUniquePath ) { log . info ( "Pushing segments in background: [%s]" , Joiner . on ( ", " ) . join ( segmentIdentifiers ) ) ; return Futur...
Push the given segments in background .
18,949
private int tryReserveEventSizeAndLock ( long state , int size ) { Preconditions . checkArgument ( size > 0 ) ; int bufferWatermark = bufferWatermark ( state ) ; while ( true ) { if ( compareAndSetState ( state , state + size + PARTY ) ) { return bufferWatermark ; } state = getState ( ) ; if ( isSealed ( state ) ) { re...
Returns the buffer offset at which the caller has reserved the ability to write size bytes exclusively or negative number if the reservation attempt failed .
18,950
public static void serialize ( OutputStream out , BloomKFilter bloomFilter ) throws IOException { DataOutputStream dataOutputStream = new DataOutputStream ( out ) ; dataOutputStream . writeByte ( bloomFilter . k ) ; dataOutputStream . writeInt ( bloomFilter . getBitSet ( ) . length ) ; for ( long value : bloomFilter . ...
Serialize a bloom filter
18,951
public static void serialize ( ByteBuffer out , int position , BloomKFilter bloomFilter ) { ByteBuffer view = out . duplicate ( ) . order ( ByteOrder . BIG_ENDIAN ) ; view . position ( position ) ; view . put ( ( byte ) bloomFilter . k ) ; view . putInt ( bloomFilter . getBitSet ( ) . length ) ; for ( long value : bloo...
Serialize a bloom filter to a ByteBuffer . Does not mutate buffer position .
18,952
public static int computeSizeBytes ( long maxNumEntries ) { checkArgument ( maxNumEntries > 0 , "expectedEntries should be > 0" ) ; long numBits = optimalNumOfBits ( maxNumEntries , DEFAULT_FPP ) ; int nLongs = ( int ) Math . ceil ( ( double ) numBits / ( double ) Long . SIZE ) ; int padLongs = DEFAULT_BLOCK_SIZE - nLo...
Calculate size in bytes of a BloomKFilter for a given number of entries
18,953
public void merge ( BloomKFilter that ) { if ( this != that && this . m == that . m && this . k == that . k ) { this . bitSet . putAll ( that . bitSet ) ; } else { throw new IllegalArgumentException ( "BloomKFilters are not compatible for merging." + " this - " + this + " that - " + that ) ; } }
Merge the specified bloom filter with current bloom filter .
18,954
public Boolean isHandOffComplete ( String dataSource , SegmentDescriptor descriptor ) { try { FullResponseHolder response = druidLeaderClient . go ( druidLeaderClient . makeRequest ( HttpMethod . GET , StringUtils . format ( "/druid/coordinator/v1/datasources/%s/handoffComplete?interval=%s&partitionNumber=%d&version=%s...
Checks the given segment is handed off or not . It can return null if the HTTP call returns 404 which can happen during rolling update .
18,955
public static boolean sortingOrderHasNonGroupingFields ( DefaultLimitSpec limitSpec , List < DimensionSpec > dimensions ) { for ( OrderByColumnSpec orderSpec : limitSpec . getColumns ( ) ) { int dimIndex = OrderByColumnSpec . getDimIndexForOrderBy ( orderSpec , dimensions ) ; if ( dimIndex < 0 ) { return true ; } } ret...
Check if a limitSpec has columns in the sorting order that are not part of the grouping fields represented by dimensions .
18,956
public static < T > MapBinder < String , T > optionBinder ( Binder binder , Key < T > interfaceKey ) { final TypeLiteral < T > interfaceType = interfaceKey . getTypeLiteral ( ) ; if ( interfaceKey . getAnnotation ( ) != null ) { return MapBinder . newMapBinder ( binder , TypeLiteral . get ( String . class ) , interface...
Binds an option for a specific choice . The choice must already be registered on the injector for this to work .
18,957
public void offer ( float value ) { if ( value < min ) { min = value ; } if ( value > max ) { max = value ; } if ( binCount == 0 ) { positions [ 0 ] = value ; bins [ 0 ] = 1 ; count ++ ; binCount ++ ; return ; } final int index = Arrays . binarySearch ( positions , 0 , binCount , value ) ; if ( index >= 0 ) { bins [ in...
Adds the given value to the histogram
18,958
protected void shiftRight ( int start , int end ) { float prevVal = positions [ start ] ; long prevCnt = bins [ start ] ; for ( int i = start + 1 ; i <= end ; ++ i ) { float tmpVal = positions [ i ] ; long tmpCnt = bins [ i ] ; positions [ i ] = prevVal ; bins [ i ] = prevCnt ; prevVal = tmpVal ; prevCnt = tmpCnt ; } }
Shifts the given range the histogram bins one slot to the right
18,959
protected void shiftLeft ( int start , int end ) { for ( int i = start ; i < end ; ++ i ) { positions [ i ] = positions [ i + 1 ] ; bins [ i ] = bins [ i + 1 ] ; } }
Shifts the given range of histogram bins one slot to the left
18,960
public ApproximateHistogram copy ( ApproximateHistogram h ) { if ( h . size > this . size ) { this . size = h . size ; this . positions = new float [ size ] ; this . bins = new long [ size ] ; } System . arraycopy ( h . positions , 0 , this . positions , 0 , h . binCount ) ; System . arraycopy ( h . bins , 0 , this . b...
Copies histogram h into the current histogram .
18,961
protected ApproximateHistogram foldMin ( ApproximateHistogram h , float [ ] mergedPositions , long [ ] mergedBins , float [ ] deltas ) { float mergedMin = this . min < h . min ? this . min : h . min ; float mergedMax = this . max > h . max ? this . max : h . max ; long mergedCount = this . count + h . count ; int maxSi...
approximate histogram solution using min heap to store location of min deltas
18,962
private static void mergeBins ( int mergedBinCount , float [ ] mergedPositions , long [ ] mergedBins , float [ ] deltas , int numMerge , int [ ] next , int [ ] prev ) { int lastValidIndex = mergedBinCount - 1 ; for ( int i = 0 ; i < mergedBinCount ; ++ i ) { next [ i ] = i + 1 ; } for ( int i = 0 ; i < mergedBinCount ;...
mergeBins performs the given number of bin merge operations on the given histogram
18,963
private static void heapify ( int [ ] heap , int [ ] reverseIndex , int count , float [ ] values ) { int start = ( count - 2 ) / 2 ; while ( start >= 0 ) { siftDown ( heap , reverseIndex , start , count - 1 , values ) ; start -- ; } }
Builds a min - heap and a reverseIndex into the heap from the given array of values
18,964
private static void siftDown ( int [ ] heap , int [ ] reverseIndex , int start , int end , float [ ] values ) { int root = start ; while ( root * 2 + 1 <= end ) { int child = root * 2 + 1 ; int swap = root ; if ( values [ heap [ swap ] ] > values [ heap [ child ] ] ) { swap = child ; } if ( child + 1 <= end && values [...
Rebalances the min - heap by pushing values from the top down and simultaneously updating the reverse index
18,965
private static int heapDelete ( int [ ] heap , int [ ] reverseIndex , int count , int heapIndex , float [ ] values ) { int end = count - 1 ; reverseIndex [ heap [ heapIndex ] ] = - 1 ; heap [ heapIndex ] = heap [ end ] ; reverseIndex [ heap [ heapIndex ] ] = heapIndex ; end -- ; siftDown ( heap , reverseIndex , heapInd...
Deletes an item from the min - heap and updates the reverse index
18,966
private static int combineBins ( int leftBinCount , float [ ] leftPositions , long [ ] leftBins , int rightBinCount , float [ ] rightPositions , long [ ] rightBins , float [ ] mergedPositions , long [ ] mergedBins , float [ ] deltas ) { int i = 0 ; int j = 0 ; int k = 0 ; while ( j < leftBinCount || k < rightBinCount )...
Combines two sets of histogram bins using merge - sort and computes the delta between consecutive bin positions . Duplicate bins are merged together .
18,967
public byte [ ] toBytes ( ) { ByteBuffer buf = ByteBuffer . allocate ( getMinStorageSize ( ) ) ; toBytes ( buf ) ; return buf . array ( ) ; }
Returns a byte - array representation of this ApproximateHistogram object
18,968
public boolean canStoreCompact ( ) { final long exactCount = getExactCount ( ) ; return ( size <= Short . MAX_VALUE && exactCount <= Byte . MAX_VALUE && ( count - exactCount ) <= Byte . MAX_VALUE ) ; }
Checks whether this approximate histogram can be stored in a compact form
18,969
public void toBytes ( ByteBuffer buf ) { if ( canStoreCompact ( ) && getCompactStorageSize ( ) < getSparseStorageSize ( ) ) { toBytesCompact ( buf ) ; } else { toBytesSparse ( buf ) ; } }
Writes the representation of this ApproximateHistogram object to the given byte - buffer
18,970
public void toBytesDense ( ByteBuffer buf ) { buf . putInt ( size ) ; buf . putInt ( binCount ) ; buf . asFloatBuffer ( ) . put ( positions ) ; buf . position ( buf . position ( ) + Float . BYTES * positions . length ) ; buf . asLongBuffer ( ) . put ( bins ) ; buf . position ( buf . position ( ) + Long . BYTES * bins ....
Writes the dense representation of this ApproximateHistogram object to the given byte - buffer
18,971
public void toBytesSparse ( ByteBuffer buf ) { buf . putInt ( size ) ; buf . putInt ( - 1 * binCount ) ; for ( int i = 0 ; i < binCount ; ++ i ) { buf . putFloat ( positions [ i ] ) ; } for ( int i = 0 ; i < binCount ; ++ i ) { buf . putLong ( bins [ i ] ) ; } buf . putFloat ( min ) ; buf . putFloat ( max ) ; }
Writes the sparse representation of this ApproximateHistogram object to the given byte - buffer
18,972
public void toBytesCompact ( ByteBuffer buf ) { Preconditions . checkState ( canStoreCompact ( ) , "Approximate histogram cannot be stored in compact form" ) ; buf . putShort ( ( short ) ( - 1 * size ) ) ; final long exactCount = getExactCount ( ) ; if ( exactCount != count ) { buf . put ( ( byte ) ( - 1 * ( count - ex...
Returns a compact byte - buffer representation of this ApproximateHistogram object storing actual values as opposed to histogram bins
18,973
public static ApproximateHistogram fromBytes ( byte [ ] bytes ) { ByteBuffer buf = ByteBuffer . wrap ( bytes ) ; return fromBytes ( buf ) ; }
Constructs an Approximate Histogram object from the given byte - array representation
18,974
public static ApproximateHistogram fromBytesCompact ( ByteBuffer buf ) { short size = ( short ) ( - 1 * buf . getShort ( ) ) ; byte count = buf . get ( ) ; if ( count >= 0 ) { ApproximateHistogram histogram = new ApproximateHistogram ( size ) ; for ( int i = 0 ; i < count ; ++ i ) { histogram . offer ( buf . getFloat (...
Constructs an ApproximateHistogram object from the given compact byte - buffer representation
18,975
public static ApproximateHistogram fromBytes ( ByteBuffer buf ) { if ( buf . getShort ( buf . position ( ) ) < 0 ) { return fromBytesCompact ( buf ) ; } else { if ( buf . getInt ( buf . position ( ) + Integer . BYTES ) < 0 ) { return fromBytesSparse ( buf ) ; } else { return fromBytesDense ( buf ) ; } } }
Constructs an ApproximateHistogram object from the given byte - buffer representation
18,976
public double sum ( final float b ) { if ( b < min ) { return 0 ; } if ( b >= max ) { return count ; } int index = Arrays . binarySearch ( positions , 0 , binCount , b ) ; boolean exactMatch = index >= 0 ; index = exactMatch ? index : - ( index + 1 ) ; if ( ! exactMatch ) { index -- ; } final boolean outerLeft = index ...
Returns the approximate number of items less than or equal to b in the histogram
18,977
public Histogram toHistogram ( final float [ ] breaks ) { final double [ ] approximateBins = new double [ breaks . length - 1 ] ; double prev = sum ( breaks [ 0 ] ) ; for ( int i = 1 ; i < breaks . length ; ++ i ) { double s = sum ( breaks [ i ] ) ; approximateBins [ i - 1 ] = ( float ) ( s - prev ) ; prev = s ; } retu...
Computes a visual representation of the approximate histogram with bins laid out according to the given breaks
18,978
public Histogram toHistogram ( int size ) { Preconditions . checkArgument ( size > 1 , "histogram size must be greater than 1" ) ; float [ ] breaks = new float [ size + 1 ] ; float delta = ( max - min ) / ( size - 1 ) ; breaks [ 0 ] = min - delta ; for ( int i = 1 ; i < breaks . length - 1 ; ++ i ) { breaks [ i ] = bre...
Computes a visual representation of the approximate histogram with a given number of equal - sized bins
18,979
public Histogram toHistogram ( final float bucketSize , final float offset ) { final float minFloor = ( float ) Math . floor ( ( min ( ) - offset ) / bucketSize ) * bucketSize + offset ; final float lowerLimitFloor = ( float ) Math . floor ( ( lowerLimit - offset ) / bucketSize ) * bucketSize + offset ; final float fir...
Computes a visual representation given an initial breakpoint offset and a bucket size .
18,980
public Optional < Bucket > getBucket ( InputRow inputRow ) { final Optional < Interval > timeBucket = schema . getDataSchema ( ) . getGranularitySpec ( ) . bucketInterval ( DateTimes . utc ( inputRow . getTimestampFromEpoch ( ) ) ) ; if ( ! timeBucket . isPresent ( ) ) { return Optional . absent ( ) ; } final DateTime ...
Get the proper bucket for some input row .
18,981
public Path makeIntermediatePath ( ) { return new Path ( StringUtils . format ( "%s/%s/%s_%s" , getWorkingPath ( ) , schema . getDataSchema ( ) . getDataSource ( ) , StringUtils . removeChar ( schema . getTuningConfig ( ) . getVersion ( ) , ':' ) , schema . getUniqueId ( ) ) ) ; }
Make the intermediate path for this job run .
18,982
public LookupExtractor get ( ) { final Lock readLock = startStopSync . readLock ( ) ; try { readLock . lockInterruptibly ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } try { if ( entry == null ) { throw new ISE ( "Factory [%s] not started" , extractorID ) ; } final CacheScheduler . Cach...
Grab the latest snapshot from the CacheScheduler s entry
18,983
private static void addInputPath ( Job job , Iterable < String > pathStrings , Class < ? extends InputFormat > inputFormatClass ) { Configuration conf = job . getConfiguration ( ) ; StringBuilder inputFormats = new StringBuilder ( StringUtils . nullToEmptyNonDruidDataString ( conf . get ( MultipleInputs . DIR_FORMATS )...
copied from MultipleInputs . addInputPath with slight modifications
18,984
public static FileCopyResult retryCopy ( final ByteSource byteSource , final File outFile , final Predicate < Throwable > shouldRetry , final int maxAttempts ) { try { StreamUtils . retryCopy ( byteSource , Files . asByteSink ( outFile ) , shouldRetry , maxAttempts ) ; return new FileCopyResult ( outFile ) ; } catch ( ...
Copy input byte source to outFile . If outFile exists it is attempted to be deleted .
18,985
public ListenableFuture < TaskStatus > run ( final Task task ) { final RemoteTaskRunnerWorkItem completeTask , runningTask , pendingTask ; if ( ( pendingTask = pendingTasks . get ( task . getId ( ) ) ) != null ) { log . info ( "Assigned a task[%s] that is already pending!" , task . getId ( ) ) ; runPendingTasks ( ) ; r...
A task will be run only if there is no current knowledge in the RemoteTaskRunner of the task .
18,986
public void shutdown ( final String taskId , String reason ) { log . info ( "Shutdown [%s] because: [%s]" , taskId , reason ) ; if ( ! lifecycleLock . awaitStarted ( 1 , TimeUnit . SECONDS ) ) { log . info ( "This TaskRunner is stopped or not yet started. Ignoring shutdown command for task: %s" , taskId ) ; } else if (...
Finds the worker running the task and forwards the shutdown signal to the worker .
18,987
private void runPendingTasks ( ) { runPendingTasksExec . submit ( new Callable < Void > ( ) { public Void call ( ) { try { List < RemoteTaskRunnerWorkItem > copy = Lists . newArrayList ( pendingTasks . values ( ) ) ; sortByInsertionTime ( copy ) ; for ( RemoteTaskRunnerWorkItem taskRunnerWorkItem : copy ) { String task...
This method uses a multi - threaded executor to extract all pending tasks and attempt to run them . Any tasks that are successfully assigned to a worker will be moved from pendingTasks to runningTasks . This method is thread - safe . This method should be run each time there is new worker capacity or if new tasks are a...
18,988
private void cleanup ( final String taskId ) { if ( ! lifecycleLock . awaitStarted ( 1 , TimeUnit . SECONDS ) ) { return ; } final RemoteTaskRunnerWorkItem removed = completeTasks . remove ( taskId ) ; final Worker worker = removed . getWorker ( ) ; if ( removed == null || worker == null ) { log . makeAlert ( "WTF?! As...
Removes a task from the complete queue and clears out the ZK status path of the task .
18,989
private boolean tryAssignTask ( final Task task , final RemoteTaskRunnerWorkItem taskRunnerWorkItem ) throws Exception { Preconditions . checkNotNull ( task , "task" ) ; Preconditions . checkNotNull ( taskRunnerWorkItem , "taskRunnerWorkItem" ) ; Preconditions . checkArgument ( task . getId ( ) . equals ( taskRunnerWor...
Ensures no workers are already running a task before assigning the task to a worker . It is possible that a worker is running a task that the RTR has no knowledge of . This occurs when the RTR needs to bootstrap after a restart .
18,990
private boolean announceTask ( final Task task , final ZkWorker theZkWorker , final RemoteTaskRunnerWorkItem taskRunnerWorkItem ) throws Exception { Preconditions . checkArgument ( task . getId ( ) . equals ( taskRunnerWorkItem . getTaskId ( ) ) , "task id != workItem id" ) ; final String worker = theZkWorker . getWork...
Creates a ZK entry under a specific path associated with a worker . The worker is responsible for removing the task ZK entry and creating a task status ZK entry .
18,991
private void updateWorker ( final Worker worker ) { final ZkWorker zkWorker = zkWorkers . get ( worker . getHost ( ) ) ; if ( zkWorker != null ) { log . info ( "Worker[%s] updated its announcement from[%s] to[%s]." , worker . getHost ( ) , zkWorker . getWorker ( ) , worker ) ; zkWorker . setWorker ( worker ) ; } else {...
We allow workers to change their own capacities and versions . They cannot change their own hosts or ips without dropping themselves and re - announcing .
18,992
private void removeWorker ( final Worker worker ) { log . info ( "Kaboom! Worker[%s] removed!" , worker . getHost ( ) ) ; final ZkWorker zkWorker = zkWorkers . get ( worker . getHost ( ) ) ; if ( zkWorker != null ) { try { scheduleTasksCleanupForWorker ( worker . getHost ( ) , getAssignedTasks ( worker ) ) ; } catch ( ...
When a ephemeral worker node disappears from ZK incomplete running tasks will be retried by the logic in the status listener . We still have to make sure there are no tasks assigned to the worker but not yet running .
18,993
private void scheduleTasksCleanupForWorker ( final String worker , final List < String > tasksToFail ) { cancelWorkerCleanup ( worker ) ; final ListenableScheduledFuture < ? > cleanupTask = cleanupExec . schedule ( new Runnable ( ) { public void run ( ) { log . info ( "Running scheduled cleanup for Worker[%s]" , worker...
Schedule a task that will at some point in the future clean up znodes and issue failures for tasksToFail if they are being run by worker .
18,994
private int persistHydrant ( FireHydrant indexToPersist , SegmentIdWithShardSpec identifier ) { synchronized ( indexToPersist ) { if ( indexToPersist . hasSwapped ( ) ) { log . info ( "Segment[%s], Hydrant[%s] already swapped. Ignoring request to persist." , identifier , indexToPersist ) ; return 0 ; } log . info ( "Se...
Persists the given hydrant and returns the number of rows persisted . Must only be called in the single - threaded persistExecutor .
18,995
public static DateTime getUniversalTimestamp ( final GroupByQuery query ) { final Granularity gran = query . getGranularity ( ) ; final String timestampStringFromContext = query . getContextValue ( CTX_KEY_FUDGE_TIMESTAMP , "" ) ; if ( ! timestampStringFromContext . isEmpty ( ) ) { return DateTimes . utc ( Long . parse...
If query has a single universal timestamp return it . Otherwise return null . This is useful for keeping timestamps in sync across partial queries that may have different intervals .
18,996
public static List < PostAggregator > pruneDependentPostAgg ( List < PostAggregator > postAggregatorList , String postAggName ) { ArrayList < PostAggregator > rv = new ArrayList < > ( ) ; Set < String > deps = new HashSet < > ( ) ; deps . add ( postAggName ) ; for ( PostAggregator agg : Lists . reverse ( postAggregator...
returns the list of dependent postAggregators that should be calculated in order to calculate given postAgg
18,997
public DruidNodeDiscovery getForService ( String serviceName ) { return serviceDiscoveryMap . computeIfAbsent ( serviceName , service -> { Set < NodeType > nodeTypesToWatch = DruidNodeDiscoveryProvider . SERVICE_TO_NODE_TYPES . get ( service ) ; if ( nodeTypesToWatch == null ) { throw new IAE ( "Unknown service [%s]." ...
Get DruidNodeDiscovery instance to discover nodes that announce given service in its metadata .
18,998
private < T > Sequence < T > run ( final QueryPlus < T > queryPlus , final Map < String , Object > responseContext , final UnaryOperator < TimelineLookup < String , ServerSelector > > timelineConverter ) { return new SpecificQueryRunnable < > ( queryPlus , responseContext ) . run ( timelineConverter ) ; }
Run a query . The timelineConverter will be given the master timeline and can be used to return a different timeline if desired . This is used by getQueryRunnerForSegments .
18,999
private static int aggregateDimValue ( final int [ ] positions , final BufferAggregator [ ] theAggregators , final ByteBuffer resultsBuf , final int numBytesPerRecord , final int [ ] aggregatorOffsets , final int aggSize , final int aggExtra , final int dimIndex , int currentPosition ) { if ( SKIP_POSITION_VALUE == pos...
Returns a new currentPosition incremented if a new position was initialized otherwise the same position as passed in the last argument .