idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
12,100
public LongToken getToken ( ByteBuffer key ) { if ( key . remaining ( ) == 0 ) return MINIMUM ; long [ ] hash = new long [ 2 ] ; MurmurHash . hash3_x64_128 ( key , key . position ( ) , key . remaining ( ) , 0 , hash ) ; return new LongToken ( normalize ( hash [ 0 ] ) ) ; }
Generate the token of a key . Note that we need to ensure all generated token are strictly bigger than MINIMUM . In particular we don t want MINIMUM to correspond to any key because the range ( MINIMUM X ] doesn t include MINIMUM but we use such range to select all data whose token is smaller than X .
84
70
12,101
private static BigInteger bigForString ( String str , int sigchars ) { assert str . length ( ) <= sigchars ; BigInteger big = BigInteger . ZERO ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { int charpos = 16 * ( sigchars - ( i + 1 ) ) ; BigInteger charbig = BigInteger . valueOf ( str . charAt ( i ) & 0xFFFF ) ; bi...
Copies the characters of the given string into a BigInteger .
121
13
12,102
private void setupDefaultUser ( ) { try { // insert the default superuser if AUTH_KS.CREDENTIALS_CF is empty. if ( ! hasExistingUsers ( ) ) { process ( String . format ( "INSERT INTO %s.%s (username, salted_hash) VALUES ('%s', '%s') USING TIMESTAMP 0" , Auth . AUTH_KS , CREDENTIALS_CF , DEFAULT_USER_NAME , escape ( has...
if there are no users yet - add default superuser .
188
12
12,103
public synchronized void received ( SSTableWriter sstable ) { if ( done ) return ; assert cfId . equals ( sstable . metadata . cfId ) ; sstables . add ( sstable ) ; if ( sstables . size ( ) == totalFiles ) { done = true ; executor . submit ( new OnCompletionRunnable ( this ) ) ; } }
Process received file .
81
4
12,104
< V > void find ( Object [ ] node , Comparator < V > comparator , Object target , Op mode , boolean forwards ) { // TODO : should not require parameter 'forwards' - consider modifying index to represent both // child and key position, as opposed to just key position (which necessitates a different value depending // on...
Find the provided key in the tree rooted at node and store the root to it in the path
412
19
12,105
void successor ( ) { Object [ ] node = currentNode ( ) ; int i = currentIndex ( ) ; if ( ! isLeaf ( node ) ) { // if we're on a key in a branch, we MUST have a descendant either side of us, // so we always go down the left-most child until we hit a leaf node = ( Object [ ] ) node [ getBranchKeyEnd ( node ) + i + 1 ] ; ...
move to the next key in the tree
300
8
12,106
protected Tuple composeComposite ( AbstractCompositeType comparator , ByteBuffer name ) throws IOException { List < CompositeComponent > result = comparator . deconstruct ( name ) ; Tuple t = TupleFactory . getInstance ( ) . newTuple ( result . size ( ) ) ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) setTupleValue...
Deconstructs a composite type to a Tuple .
121
12
12,107
protected Tuple columnToTuple ( Cell col , CfInfo cfInfo , AbstractType comparator ) throws IOException { CfDef cfDef = cfInfo . cfDef ; Tuple pair = TupleFactory . getInstance ( ) . newTuple ( 2 ) ; ByteBuffer colName = col . name ( ) . toByteBuffer ( ) ; // name if ( comparator instanceof AbstractCompositeType ) setT...
convert a column to a tuple
341
7
12,108
protected CfInfo getCfInfo ( String signature ) throws IOException { UDFContext context = UDFContext . getUDFContext ( ) ; Properties property = context . getUDFProperties ( AbstractCassandraStorage . class ) ; String prop = property . getProperty ( signature ) ; CfInfo cfInfo = new CfInfo ( ) ; cfInfo . cfDef = cfdefF...
get the columnfamily definition for the signature
143
8
12,109
protected Map < MarshallerType , AbstractType > getDefaultMarshallers ( CfDef cfDef ) throws IOException { Map < MarshallerType , AbstractType > marshallers = new EnumMap < MarshallerType , AbstractType > ( MarshallerType . class ) ; AbstractType comparator ; AbstractType subcomparator ; AbstractType default_validator ...
construct a map to store the mashaller type to cassandra data type mapping
259
16
12,110
protected Map < ByteBuffer , AbstractType > getValidatorMap ( CfDef cfDef ) throws IOException { Map < ByteBuffer , AbstractType > validators = new HashMap < ByteBuffer , AbstractType > ( ) ; for ( ColumnDef cd : cfDef . getColumn_metadata ( ) ) { if ( cd . getValidation_class ( ) != null && ! cd . getValidation_class ...
get the validators
195
4
12,111
protected AbstractType parseType ( String type ) throws IOException { try { // always treat counters like longs, specifically CCT.compose is not what we need if ( type != null && type . equals ( "org.apache.cassandra.db.marshal.CounterColumnType" ) ) return LongType . instance ; return TypeParser . parse ( type ) ; } c...
parse the string to a cassandra data type
115
9
12,112
public static Map < String , String > getQueryMap ( String query ) throws UnsupportedEncodingException { String [ ] params = query . split ( "&" ) ; Map < String , String > map = new HashMap < String , String > ( ) ; for ( String param : params ) { String [ ] keyValue = param . split ( "=" ) ; map . put ( keyValue [ 0 ...
decompose the query to store the parameters in a map
112
12
12,113
protected byte getPigType ( AbstractType type ) { if ( type instanceof LongType || type instanceof DateType || type instanceof TimestampType ) // DateType is bad and it should feel bad return DataType . LONG ; else if ( type instanceof IntegerType || type instanceof Int32Type ) // IntegerType will overflow at 2**31, bu...
get pig type for the cassandra data type
205
9
12,114
protected ByteBuffer objToBB ( Object o ) { if ( o == null ) return nullToBB ( ) ; if ( o instanceof java . lang . String ) return ByteBuffer . wrap ( new DataByteArray ( ( String ) o ) . get ( ) ) ; if ( o instanceof Integer ) return Int32Type . instance . decompose ( ( Integer ) o ) ; if ( o instanceof Long ) return ...
convert object to ByteBuffer
363
6
12,115
protected void initSchema ( String signature ) throws IOException { Properties properties = UDFContext . getUDFContext ( ) . getUDFProperties ( AbstractCassandraStorage . class ) ; // Only get the schema if we haven't already gotten it if ( ! properties . containsKey ( signature ) ) { try { Cassandra . Client client = ...
Methods to get the column family schema from Cassandra
400
9
12,116
protected static String cfdefToString ( CfDef cfDef ) throws IOException { assert cfDef != null ; // this is so awful it's kind of cool! TSerializer serializer = new TSerializer ( new TBinaryProtocol . Factory ( ) ) ; try { return Hex . bytesToHex ( serializer . serialize ( cfDef ) ) ; } catch ( TException e ) { throw ...
convert CfDef to string
95
6
12,117
protected static CfDef cfdefFromString ( String st ) throws IOException { assert st != null ; TDeserializer deserializer = new TDeserializer ( new TBinaryProtocol . Factory ( ) ) ; CfDef cfDef = new CfDef ( ) ; try { deserializer . deserialize ( cfDef , Hex . hexToBytes ( st ) ) ; } catch ( TException e ) { throw new I...
convert string back to CfDef
102
7
12,118
protected CfInfo getCfInfo ( Cassandra . Client client ) throws InvalidRequestException , UnavailableException , TimedOutException , SchemaDisagreementException , TException , NotFoundException , org . apache . cassandra . exceptions . InvalidRequestException , ConfigurationException , IOException { // get CF meta data...
return the CfInfo for the column family
625
8
12,119
protected List < ColumnDef > getColumnMeta ( Cassandra . Client client , boolean cassandraStorage , boolean includeCompactValueColumn ) throws InvalidRequestException , UnavailableException , TimedOutException , SchemaDisagreementException , TException , CharacterCodingException , org . apache . cassandra . exceptions ...
get column meta data
768
4
12,120
protected IndexType getIndexType ( String type ) { type = type . toLowerCase ( ) ; if ( "keys" . equals ( type ) ) return IndexType . KEYS ; else if ( "custom" . equals ( type ) ) return IndexType . CUSTOM ; else if ( "composites" . equals ( type ) ) return IndexType . COMPOSITES ; else return null ; }
get index type from string
87
5
12,121
public String [ ] getPartitionKeys ( String location , Job job ) throws IOException { if ( ! usePartitionFilter ) return null ; List < ColumnDef > indexes = getIndexes ( ) ; String [ ] partitionKeys = new String [ indexes . size ( ) ] ; for ( int i = 0 ; i < indexes . size ( ) ; i ++ ) { partitionKeys [ i ] = new Strin...
return partition keys
106
3
12,122
protected List < ColumnDef > getIndexes ( ) throws IOException { CfDef cfdef = getCfInfo ( loadSignature ) . cfDef ; List < ColumnDef > indexes = new ArrayList < ColumnDef > ( ) ; for ( ColumnDef cdef : cfdef . column_metadata ) { if ( cdef . index_type != null ) indexes . add ( cdef ) ; } return indexes ; }
get a list of columns with defined index
89
8
12,123
protected CFMetaData getCFMetaData ( String ks , String cf , Cassandra . Client client ) throws NotFoundException , InvalidRequestException , TException , org . apache . cassandra . exceptions . InvalidRequestException , ConfigurationException { KsDef ksDef = client . describe_keyspace ( ks ) ; for ( CfDef cfDef : ksDe...
get CFMetaData of a column family
118
8
12,124
public void commit ( ) { Log . info ( "Committing" ) ; try { indexWriter . commit ( ) ; } catch ( IOException e ) { Log . error ( e , "Error while committing" ) ; throw new RuntimeException ( e ) ; } }
Commits the pending changes .
56
6
12,125
public void close ( ) { Log . info ( "Closing index" ) ; try { Log . info ( "Closing" ) ; searcherReopener . interrupt ( ) ; searcherManager . close ( ) ; indexWriter . close ( ) ; directory . close ( ) ; } catch ( IOException e ) { Log . error ( e , "Error while closing index" ) ; throw new RuntimeException ( e ) ; } ...
Commits all changes to the index waits for pending merges to complete and closes all associated resources .
92
20
12,126
public void optimize ( ) { Log . debug ( "Optimizing index" ) ; try { indexWriter . forceMerge ( 1 , true ) ; indexWriter . commit ( ) ; } catch ( IOException e ) { Log . error ( e , "Error while optimizing index" ) ; throw new RuntimeException ( e ) ; } }
Optimizes the index forcing merge segments leaving one single segment . This operation blocks until all merging completes .
71
21
12,127
private long beforeAppend ( DecoratedKey decoratedKey ) { assert decoratedKey != null : "Keys must not be null" ; // empty keys ARE allowed b/c of indexed column values if ( lastWrittenKey != null && lastWrittenKey . compareTo ( decoratedKey ) >= 0 ) throw new RuntimeException ( "Last written key " + lastWrittenKey + "...
Perform sanity checks on
118
5
12,128
public void abort ( ) { assert descriptor . type . isTemporary ; if ( iwriter == null && dataFile == null ) return ; if ( iwriter != null ) iwriter . abort ( ) ; if ( dataFile != null ) dataFile . abort ( ) ; Set < Component > components = SSTable . componentsFor ( descriptor ) ; try { if ( ! components . isEmpty ( ) )...
After failure attempt to close the index writer and data file before deleting all temp components for the sstable
135
20
12,129
public void reset ( Object [ ] btree , boolean forwards ) { _reset ( btree , null , NEGATIVE_INFINITY , false , POSITIVE_INFINITY , false , forwards ) ; }
Reset this cursor for the provided tree to iterate over its entire range
46
15
12,130
public Pair < Long , Long > addAllWithSizeDelta ( final ColumnFamily cm , MemtableAllocator allocator , OpOrder . Group writeOp , Updater indexer ) { ColumnUpdater updater = new ColumnUpdater ( this , cm . metadata , allocator , writeOp , indexer ) ; DeletionInfo inputDeletionInfoCopy = null ; boolean monitorOwned = fa...
This is only called by Memtable . resolve so only AtomicBTreeColumns needs to implement it .
489
21
12,131
private boolean updateWastedAllocationTracker ( long wastedBytes ) { // Early check for huge allocation that exceeds the limit if ( wastedBytes < EXCESS_WASTE_BYTES ) { // We round up to ensure work < granularity are still accounted for int wastedAllocation = ( ( int ) ( wastedBytes + ALLOCATION_GRANULARITY_BYTES - 1 )...
Update the wasted allocation tracker state based on newly wasted allocation information
334
12
12,132
public ByteBuffer getElement ( ByteBuffer serializedList , int index ) { try { ByteBuffer input = serializedList . duplicate ( ) ; int n = readCollectionSize ( input , Server . VERSION_3 ) ; if ( n <= index ) return null ; for ( int i = 0 ; i < index ; i ++ ) { int length = input . getInt ( ) ; input . position ( input...
Returns the element at the given index in a list .
137
11
12,133
private void releaseReferences ( ) { for ( SSTableReader sstable : sstables ) { sstable . selfRef ( ) . release ( ) ; assert sstable . selfRef ( ) . globalCount ( ) == 0 ; } }
releases the shared reference for all sstables we acquire this when opening the sstable
51
18
12,134
public TimeCounter start ( ) { switch ( state ) { case UNSTARTED : watch . start ( ) ; break ; case RUNNING : throw new IllegalStateException ( "Already started. " ) ; case STOPPED : watch . resume ( ) ; } state = State . RUNNING ; return this ; }
Starts or resumes the time count .
66
8
12,135
public TimeCounter stop ( ) { switch ( state ) { case UNSTARTED : throw new IllegalStateException ( "Not started. " ) ; case STOPPED : throw new IllegalStateException ( "Already stopped. " ) ; case RUNNING : watch . suspend ( ) ; } state = State . STOPPED ; return this ; }
Stops or suspends the time count .
72
9
12,136
public static List < TriggerDefinition > fromSchema ( Row serializedTriggers ) { List < TriggerDefinition > triggers = new ArrayList <> ( ) ; String query = String . format ( "SELECT * FROM %s.%s" , Keyspace . SYSTEM_KS , SystemKeyspace . SCHEMA_TRIGGERS_CF ) ; for ( UntypedResultSet . Row row : QueryProcessor . result...
Deserialize triggers from storage - level representation .
172
10
12,137
public void toSchema ( Mutation mutation , String cfName , long timestamp ) { ColumnFamily cf = mutation . addOrGet ( SystemKeyspace . SCHEMA_TRIGGERS_CF ) ; CFMetaData cfm = CFMetaData . SchemaTriggersCf ; Composite prefix = cfm . comparator . make ( cfName , name ) ; CFRowAdder adder = new CFRowAdder ( cf , prefix , ...
Add specified trigger to the schema using given mutation .
120
10
12,138
public void deleteFromSchema ( Mutation mutation , String cfName , long timestamp ) { ColumnFamily cf = mutation . addOrGet ( SystemKeyspace . SCHEMA_TRIGGERS_CF ) ; int ldt = ( int ) ( System . currentTimeMillis ( ) / 1000 ) ; Composite prefix = CFMetaData . SchemaTriggersCf . comparator . make ( cfName , name ) ; cf ...
Drop specified trigger from the schema using given mutation .
118
10
12,139
void clear ( ) { NodeBuilder current = this ; while ( current != null && current . upperBound != null ) { current . clearSelf ( ) ; current = current . child ; } current = parent ; while ( current != null && current . upperBound != null ) { current . clearSelf ( ) ; current = current . parent ; } }
ensure we aren t referencing any garbage
72
8
12,140
NodeBuilder update ( Object key ) { assert copyFrom != null ; int copyFromKeyEnd = getKeyEnd ( copyFrom ) ; int i = copyFromKeyPosition ; boolean found ; // exact key match? boolean owns = true ; // true iff this node (or a child) should contain the key if ( i == copyFromKeyEnd ) { found = false ; } else { // this opti...
Inserts or replaces the provided key copying all not - yet - visited keys prior to it into our buffer .
796
22
12,141
NodeBuilder ascendToRoot ( ) { NodeBuilder current = this ; while ( ! current . isRoot ( ) ) current = current . ascend ( ) ; return current ; }
where we work only on the newest child node which may construct many spill - over parents as it goes
36
20
12,142
Object [ ] toNode ( ) { assert buildKeyPosition <= FAN_FACTOR && ( buildKeyPosition > 0 || copyFrom . length > 0 ) : buildKeyPosition ; return buildFromRange ( 0 , buildKeyPosition , isLeaf ( copyFrom ) , false ) ; }
builds a new root BTree node - must be called on root of operation
62
16
12,143
private NodeBuilder ascend ( ) { ensureParent ( ) ; boolean isLeaf = isLeaf ( copyFrom ) ; if ( buildKeyPosition > FAN_FACTOR ) { // split current node and move the midpoint into parent, with the two halves as children int mid = buildKeyPosition / 2 ; parent . addExtraChild ( buildFromRange ( 0 , mid , isLeaf , true ) ...
finish up this level and pass any constructed children up to our parent ensuring a parent exists
156
18
12,144
void addNewKey ( Object key ) { ensureRoom ( buildKeyPosition + 1 ) ; buildKeys [ buildKeyPosition ++ ] = updateFunction . apply ( key ) ; }
puts the provided key in the builder with no impact on treatment of data from copyf
37
18
12,145
private void addExtraChild ( Object [ ] child , Object upperBound ) { ensureRoom ( buildKeyPosition + 1 ) ; buildKeys [ buildKeyPosition ++ ] = upperBound ; buildChildren [ buildChildPosition ++ ] = child ; }
adds a new and unexpected child to the builder - called by children that overflow
50
16
12,146
private void ensureRoom ( int nextBuildKeyPosition ) { if ( nextBuildKeyPosition < MAX_KEYS ) return ; // flush even number of items so we don't waste leaf space repeatedly Object [ ] flushUp = buildFromRange ( 0 , FAN_FACTOR , isLeaf ( copyFrom ) , true ) ; ensureParent ( ) . addExtraChild ( flushUp , buildKeys [ FAN_...
checks if we can add the requested keys + children to the builder and if not we spill - over into our parent
202
23
12,147
private Object [ ] buildFromRange ( int offset , int keyLength , boolean isLeaf , boolean isExtra ) { // if keyLength is 0, we didn't copy anything from the original, which means we didn't // modify any of the range owned by it, so can simply return it as is if ( keyLength == 0 ) return copyFrom ; Object [ ] a ; if ( i...
builds and returns a node from the buffered objects in the given range
256
15
12,148
private NodeBuilder ensureParent ( ) { if ( parent == null ) { parent = new NodeBuilder ( ) ; parent . child = this ; } if ( parent . upperBound == null ) parent . reset ( EMPTY_BRANCH , upperBound , updateFunction , comparator ) ; return parent ; }
already be initialised and only aren t in the case where we are overflowing the original root node
64
20
12,149
private List < Pair < Long , Long > > getTransferSections ( CompressionMetadata . Chunk [ ] chunks ) { List < Pair < Long , Long > > transferSections = new ArrayList <> ( ) ; Pair < Long , Long > lastSection = null ; for ( CompressionMetadata . Chunk chunk : chunks ) { if ( lastSection != null ) { if ( chunk . offset =...
chunks are assumed to be sorted by offset
221
9
12,150
@ Override public CellName copy ( CFMetaData cfm , AbstractAllocator allocator ) { return new SimpleDenseCellName ( allocator . clone ( element ) ) ; }
we might want to try to do better .
40
9
12,151
private long getNow ( ) { return Collections . max ( cfs . getSSTables ( ) , new Comparator < SSTableReader > ( ) { public int compare ( SSTableReader o1 , SSTableReader o2 ) { return Long . compare ( o1 . getMaxTimestamp ( ) , o2 . getMaxTimestamp ( ) ) ; } } ) . getMaxTimestamp ( ) ; }
Gets the timestamp that DateTieredCompactionStrategy considers to be the current time .
91
20
12,152
@ VisibleForTesting static Iterable < SSTableReader > filterOldSSTables ( List < SSTableReader > sstables , long maxSSTableAge , long now ) { if ( maxSSTableAge == 0 ) return sstables ; final long cutoff = now - maxSSTableAge ; return Iterables . filter ( sstables , new Predicate < SSTableReader > ( ) { @ Override publ...
Removes all sstables with max timestamp older than maxSSTableAge .
124
17
12,153
@ VisibleForTesting static < T > List < List < T > > getBuckets ( Collection < Pair < T , Long > > files , long timeUnit , int base , long now ) { // Sort files by age. Newest first. final List < Pair < T , Long > > sortedFiles = Lists . newArrayList ( files ) ; Collections . sort ( sortedFiles , Collections . reverseO...
Group files with similar min timestamp into buckets . Files with recent min timestamps are grouped together into buckets designated to short timespans while files with older timestamps are grouped into buckets representing longer timespans .
384
44
12,154
@ Override public void write ( Object key , List < ByteBuffer > values ) throws IOException { prepareWriter ( ) ; try { ( ( CQLSSTableWriter ) writer ) . rawAddRow ( values ) ; if ( null != progress ) progress . progress ( ) ; if ( null != context ) HadoopCompat . progress ( context ) ; } catch ( InvalidRequestExceptio...
The column values must correspond to the order in which they appear in the insert stored procedure .
105
18
12,155
private static long discard ( ByteBuf buffer , long remainingToDiscard ) { int availableToDiscard = ( int ) Math . min ( remainingToDiscard , buffer . readableBytes ( ) ) ; buffer . skipBytes ( availableToDiscard ) ; return remainingToDiscard - availableToDiscard ; }
How much remains to be discarded
66
6
12,156
public static boolean delete ( Descriptor desc , Set < Component > components ) { // remove the DATA component first if it exists if ( components . contains ( Component . DATA ) ) FileUtils . deleteWithConfirm ( desc . filenameFor ( Component . DATA ) ) ; for ( Component component : components ) { if ( component . equa...
We use a ReferenceQueue to manage deleting files that have been compacted and for which no more SSTable references exist . But this is not guaranteed to run for each such file because of the semantics of the JVM gc . So we write a marker to compactedFilename when a file is compacted ; if such a marker exists on startup...
144
76
12,157
public static DecoratedKey getMinimalKey ( DecoratedKey key ) { return key . getKey ( ) . position ( ) > 0 || key . getKey ( ) . hasRemaining ( ) || ! key . getKey ( ) . hasArray ( ) ? new BufferDecoratedKey ( key . getToken ( ) , HeapAllocator . instance . clone ( key . getKey ( ) ) ) : key ; }
If the given
94
3
12,158
protected static Set < Component > readTOC ( Descriptor descriptor ) throws IOException { File tocFile = new File ( descriptor . filenameFor ( Component . TOC ) ) ; List < String > componentNames = Files . readLines ( tocFile , Charset . defaultCharset ( ) ) ; Set < Component > components = Sets . newHashSetWithExpecte...
Reads the list of components from the TOC component .
176
12
12,159
protected static void appendTOC ( Descriptor descriptor , Collection < Component > components ) { File tocFile = new File ( descriptor . filenameFor ( Component . TOC ) ) ; PrintWriter w = null ; try { w = new PrintWriter ( new FileWriter ( tocFile , true ) ) ; for ( Component component : components ) w . println ( com...
Appends new component names to the TOC component .
119
11
12,160
public synchronized void addComponents ( Collection < Component > newComponents ) { Collection < Component > componentsToAdd = Collections2 . filter ( newComponents , Predicates . not ( Predicates . in ( components ) ) ) ; appendTOC ( descriptor , componentsToAdd ) ; components . addAll ( componentsToAdd ) ; }
Registers new custom components . Used by custom compaction strategies . Adding a component for the second time is a no - op . Don t remove this - this method is a part of the public API intended for use by custom compaction strategies .
70
49
12,161
@ Override public void serialize ( Map < MetadataType , MetadataComponent > components , DataOutputPlus out ) throws IOException { ValidationMetadata validation = ( ValidationMetadata ) components . get ( MetadataType . VALIDATION ) ; StatsMetadata stats = ( StatsMetadata ) components . get ( MetadataType . STATS ) ; C...
Legacy serialization is only used for SSTable level reset .
409
14
12,162
@ Override public Map < MetadataType , MetadataComponent > deserialize ( Descriptor descriptor , EnumSet < MetadataType > types ) throws IOException { Map < MetadataType , MetadataComponent > components = Maps . newHashMap ( ) ; File statsFile = new File ( descriptor . filenameFor ( Component . STATS ) ) ; if ( ! stats...
Legacy serializer deserialize all components no matter what types are specified .
706
16
12,163
public void initiate ( ) throws IOException { logger . debug ( "[Stream #{}] Sending stream init for incoming stream" , session . planId ( ) ) ; Socket incomingSocket = session . createConnection ( ) ; incoming . start ( incomingSocket , StreamMessage . CURRENT_VERSION ) ; incoming . sendInitMessage ( incomingSocket , ...
Set up incoming message handler and initiate streaming .
140
9
12,164
public void initiateOnReceivingSide ( Socket socket , boolean isForOutgoing , int version ) throws IOException { if ( isForOutgoing ) outgoing . start ( socket , version ) ; else incoming . start ( socket , version ) ; }
Set up outgoing message handler on receiving side .
52
9
12,165
private void setNextSamplePosition ( long position ) { tryAgain : while ( true ) { position += minIndexInterval ; long test = indexIntervalMatches ++ ; for ( int start : startPoints ) if ( ( test - start ) % BASE_SAMPLING_LEVEL == 0 ) continue tryAgain ; nextSamplePosition = position ; return ; } }
calculate the next key we will store to our summary
77
12
12,166
public IndexSummary build ( IPartitioner partitioner , ReadableBoundary boundary ) { assert entries . length ( ) > 0 ; int count = ( int ) ( offsets . length ( ) / 4 ) ; long entriesLength = entries . length ( ) ; if ( boundary != null ) { count = boundary . summaryCount ; entriesLength = boundary . entriesLength ; } i...
multiple invocations of this build method
162
7
12,167
public static IndexSummary downsample ( IndexSummary existing , int newSamplingLevel , int minIndexInterval , IPartitioner partitioner ) { // To downsample the old index summary, we'll go through (potentially) several rounds of downsampling. // Conceptually, each round starts at position X and then removes every Nth it...
Downsamples an existing index summary to a new sampling level .
594
13
12,168
public void update ( double p , long m ) { Long mi = bin . get ( p ) ; if ( mi != null ) { // we found the same p so increment that counter bin . put ( p , mi + m ) ; } else { bin . put ( p , m ) ; // if bin size exceeds maximum bin size then trim down to max size while ( bin . size ( ) > maxBinSize ) { // find points ...
Adds new point p with value m to this histogram .
287
12
12,169
public RateLimiter getRateLimiter ( ) { double currentThroughput = DatabaseDescriptor . getCompactionThroughputMbPerSec ( ) * 1024.0 * 1024.0 ; // if throughput is set to 0, throttling is disabled if ( currentThroughput == 0 || StorageService . instance . isBootstrapMode ( ) ) currentThroughput = Double . MAX_VALUE ; i...
Gets compaction rate limiter . When compaction_throughput_mb_per_sec is 0 or node is bootstrapping this returns rate limiter with the rate of Double . MAX_VALUE bytes per second . Rate unit is bytes per sec .
122
53
12,170
private SSTableReader lookupSSTable ( final ColumnFamilyStore cfs , Descriptor descriptor ) { for ( SSTableReader sstable : cfs . getSSTables ( ) ) { if ( sstable . descriptor . equals ( descriptor ) ) return sstable ; } return null ; }
This is not efficient do not use in any critical path
64
11
12,171
public Future < Object > submitValidation ( final ColumnFamilyStore cfStore , final Validator validator ) { Callable < Object > callable = new Callable < Object > ( ) { public Object call ( ) throws IOException { try { doValidationCompaction ( cfStore , validator ) ; } catch ( Throwable e ) { // we need to inform the r...
Does not mutate data so is not scheduled .
120
10
12,172
static boolean needsCleanup ( SSTableReader sstable , Collection < Range < Token > > ownedRanges ) { assert ! ownedRanges . isEmpty ( ) ; // cleanup checks for this // unwrap and sort the ranges by LHS token List < Range < Token > > sortedRanges = Range . normalize ( ownedRanges ) ; // see if there are any keys LTE the...
Determines if a cleanup would actually remove any data in this SSTable based on a set of owned ranges .
416
24
12,173
public Future < ? > submitIndexBuild ( final SecondaryIndexBuilder builder ) { Runnable runnable = new Runnable ( ) { public void run ( ) { metrics . beginCompaction ( builder ) ; try { builder . build ( ) ; } finally { metrics . finishCompaction ( builder ) ; } } } ; if ( executor . isShutdown ( ) ) { logger . info ( ...
Is not scheduled because it is performing disjoint work from sstable compaction .
117
17
12,174
public void interruptCompactionFor ( Iterable < CFMetaData > columnFamilies , boolean interruptValidation ) { assert columnFamilies != null ; // interrupt in-progress compactions for ( Holder compactionHolder : CompactionMetrics . getCompactions ( ) ) { CompactionInfo info = compactionHolder . getCompactionInfo ( ) ; i...
Try to stop all of the compactions for given ColumnFamilies .
142
15
12,175
private void fastAddAll ( ArrayBackedSortedColumns other ) { if ( other . isInsertReversed ( ) == isInsertReversed ( ) ) { cells = Arrays . copyOf ( other . cells , other . cells . length ) ; size = other . size ; sortedSize = other . sortedSize ; isSorted = other . isSorted ; } else { if ( cells . length < other . get...
Fast path when this ABSC is empty .
180
9
12,176
private void internalRemove ( int index ) { int moving = size - index - 1 ; if ( moving > 0 ) System . arraycopy ( cells , index + 1 , cells , index , moving ) ; cells [ -- size ] = null ; }
Remove the cell at a given index shifting the rest of the array to the left if needed . Please note that we mostly remove from the end so the shifting should be rare .
51
35
12,177
private void reconcileWith ( int i , Cell cell ) { cells [ i ] = cell . reconcile ( cells [ i ] ) ; }
Reconcile with a cell at position i . Assume that i is a valid position .
28
20
12,178
private Region getRegion ( ) { while ( true ) { // Try to get the region Region region = currentRegion . get ( ) ; if ( region != null ) return region ; // No current region, so we want to allocate one. We race // against other allocators to CAS in a Region, and if we fail we stash the region for re-use region = RACE_A...
Get the current region or if there is no current region allocate a new one
234
15
12,179
public static void skipIndex ( DataInput in ) throws IOException { /* read only the column index list */ int columnIndexSize = in . readInt ( ) ; /* skip the column index data */ if ( in instanceof FileDataInput ) { FileUtils . skipBytesFully ( in , columnIndexSize ) ; } else { // skip bytes byte [ ] skip = new byte [ ...
Skip the index
97
3
12,180
public static List < IndexInfo > deserializeIndex ( FileDataInput in , CType type ) throws IOException { int columnIndexSize = in . readInt ( ) ; if ( columnIndexSize == 0 ) return Collections . < IndexInfo > emptyList ( ) ; ArrayList < IndexInfo > indexList = new ArrayList < IndexInfo > ( ) ; FileMark mark = in . mark...
Deserialize the index into a structure and return it
156
11
12,181
public Timer newTimer ( String opType , int sampleCount ) { final Timer timer = new Timer ( sampleCount ) ; if ( ! timers . containsKey ( opType ) ) timers . put ( opType , new ArrayList < Timer > ( ) ) ; timers . get ( opType ) . add ( timer ) ; return timer ; }
build a new timer and add it to the set of running timers .
75
14
12,182
@ Deprecated public void close ( org . apache . hadoop . mapred . Reporter reporter ) throws IOException { close ( ) ; }
Fills the deprecated RecordWriter interface for streaming .
30
10
12,183
static SelectStatement forSelection ( CFMetaData cfm , Selection selection ) { return new SelectStatement ( cfm , 0 , defaultParameters , selection , null ) ; }
queried data through processColumnFamily .
36
8
12,184
private boolean selectACollection ( ) { if ( ! cfm . comparator . hasCollections ( ) ) return false ; for ( ColumnDefinition def : selection . getColumns ( ) ) { if ( def . type . isCollection ( ) && def . type . isMultiCell ( ) ) return true ; } return false ; }
Returns true if a non - frozen collection is selected false otherwise .
71
13
12,185
private static Composite addEOC ( Composite composite , Bound eocBound ) { return eocBound == Bound . END ? composite . end ( ) : composite . start ( ) ; }
Adds an EOC to the specified Composite .
38
9
12,186
private static void addValue ( CBuilder builder , ColumnDefinition def , ByteBuffer value ) throws InvalidRequestException { if ( value == null ) throw new InvalidRequestException ( String . format ( "Invalid null value in condition for column %s" , def . name ) ) ; builder . add ( value ) ; }
Adds the specified value to the specified builder
66
8
12,187
void processColumnFamily ( ByteBuffer key , ColumnFamily cf , QueryOptions options , long now , Selection . ResultSetBuilder result ) throws InvalidRequestException { CFMetaData cfm = cf . metadata ( ) ; ByteBuffer [ ] keyComponents = null ; if ( cfm . getKeyValidator ( ) instanceof CompositeType ) { keyComponents = ( ...
Used by ModificationStatement for CAS operations
582
8
12,188
private boolean isRestrictedByMultipleContains ( ColumnDefinition columnDef ) { if ( ! columnDef . type . isCollection ( ) ) return false ; Restriction restriction = metadataRestrictions . get ( columnDef . name ) ; if ( ! ( restriction instanceof Contains ) ) return false ; Contains contains = ( Contains ) restriction...
Checks if the specified column is restricted by multiple contains or contains key .
92
15
12,189
synchronized void requestReport ( CountDownLatch signal ) { if ( finalReport != null ) { report = finalReport ; finalReport = new TimingInterval ( 0 ) ; signal . countDown ( ) ; } else reportRequest = signal ; }
checks to see if the timer is dead ; if not requests a report and otherwise fulfills the request itself
54
21
12,190
public synchronized void close ( ) { if ( reportRequest == null ) finalReport = buildReport ( ) ; else { finalReport = new TimingInterval ( 0 ) ; report = buildReport ( ) ; reportRequest . countDown ( ) ; reportRequest = null ; } }
closes the timer ; if a request is outstanding it furnishes the request otherwise it populates finalReport
58
21
12,191
public void write ( WritableByteChannel channel ) throws IOException { long totalSize = totalSize ( ) ; RandomAccessReader file = sstable . openDataReader ( ) ; ChecksumValidator validator = new File ( sstable . descriptor . filenameFor ( Component . CRC ) ) . exists ( ) ? DataIntegrityMetadata . checksumValidator ( ss...
Stream file of specified sections to given channel .
396
9
12,192
protected long write ( RandomAccessReader reader , ChecksumValidator validator , int start , long length , long bytesTransferred ) throws IOException { int toTransfer = ( int ) Math . min ( transferBuffer . length , length - bytesTransferred ) ; int minReadable = ( int ) Math . min ( transferBuffer . length , reader . ...
Sequentially read bytes from the file and write them to the output stream
159
14
12,193
public static long sizeOnHeapOf ( ByteBuffer [ ] array ) { long allElementsSize = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) if ( array [ i ] != null ) allElementsSize += sizeOnHeapOf ( array [ i ] ) ; return allElementsSize + sizeOfArray ( array ) ; }
Memory a ByteBuffer array consumes .
80
7
12,194
public static long sizeOnHeapOf ( ByteBuffer buffer ) { if ( buffer . isDirect ( ) ) return BUFFER_EMPTY_SIZE ; // if we're only referencing a sub-portion of the ByteBuffer, don't count the array overhead (assume it's slab // allocated, so amortized over all the allocations the overhead is negligible and better to unde...
Memory a byte buffer consumes
126
5
12,195
public static DebuggableThreadPoolExecutor createWithMaximumPoolSize ( String threadPoolName , int size , int keepAliveTime , TimeUnit unit ) { return new DebuggableThreadPoolExecutor ( size , Integer . MAX_VALUE , keepAliveTime , unit , new LinkedBlockingQueue < Runnable > ( ) , new NamedThreadFactory ( threadPoolName...
Returns a ThreadPoolExecutor with a fixed maximum number of threads but whose threads are terminated when idle for too long . When all threads are actively executing tasks new tasks are queued .
85
37
12,196
@ Override public void execute ( Runnable command ) { super . execute ( isTracing ( ) && ! ( command instanceof TraceSessionWrapper ) ? new TraceSessionWrapper < Object > ( Executors . callable ( command , null ) ) : command ) ; }
execute does not call newTaskFor
60
7
12,197
private void executeSet ( Tree statement ) throws TException , InvalidRequestException , UnavailableException , TimedOutException { if ( ! CliMain . isConnected ( ) || ! hasKeySpace ( ) ) return ; long startTime = System . nanoTime ( ) ; // ^(NODE_COLUMN_ACCESS <cf> <key> <column>) Tree columnFamilySpec = statement . g...
Execute SET statement
792
4
12,198
private void executeIncr ( Tree statement , long multiplier ) throws TException , NotFoundException , InvalidRequestException , UnavailableException , TimedOutException { if ( ! CliMain . isConnected ( ) || ! hasKeySpace ( ) ) return ; Tree columnFamilySpec = statement . getChild ( 0 ) ; String columnFamily = CliCompil...
Execute INCR statement
547
5
12,199
private void executeAddKeySpace ( Tree statement ) { if ( ! CliMain . isConnected ( ) ) return ; // first value is the keyspace name, after that it is all key=value String keyspaceName = CliUtils . unescapeSQLString ( statement . getChild ( 0 ) . getText ( ) ) ; KsDef ksDef = new KsDef ( keyspaceName , DEFAULT_PLACEMEN...
Add a keyspace
216
4