idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
131,900
public static CompressionMetadata create ( String dataFilePath ) { Descriptor desc = Descriptor . fromFilename ( dataFilePath ) ; return new CompressionMetadata ( desc . filenameFor ( Component . COMPRESSION_INFO ) , new File ( dataFilePath ) . length ( ) , desc . version . hasPostCompressionAdlerChecksums ) ; }
Create metadata about given compressed file including uncompressed data length chunk size and list of the chunk offsets of the compressed data .
131,901
boolean reset ( double useChance , int targetCount , boolean isWrite ) { this . isWrite = isWrite ; if ( this . useChance < 1d ) { Arrays . fill ( rollmodifier , 1d ) ; Arrays . fill ( chancemodifier , 1d ) ; } generator . clusteringComponents . get ( 0 ) . setSeed ( idseed ) ; int firstComponentCount = ( int ) generat...
initialise the iterator state
131,902
private int setNoLastRow ( int firstComponentCount ) { Arrays . fill ( lastRow , Integer . MAX_VALUE ) ; return firstComponentCount * generator . clusteringDescendantAverages [ 0 ] ; }
returns expected row count
131,903
private int setLastRow ( int position ) { if ( position < 0 ) throw new IllegalStateException ( ) ; decompose ( position , lastRow ) ; int expectedRowCount = 0 ; for ( int i = 0 ; i < lastRow . length ; i ++ ) { int l = lastRow [ i ] ; expectedRowCount += l * generator . clusteringDescendantAverages [ i ] ; } return ex...
returns expected distance from zero
131,904
private int compareToLastRow ( int depth ) { for ( int i = 0 ; i <= depth ; i ++ ) { int p = currentRow [ i ] , l = lastRow [ i ] , r = clusteringComponents [ i ] . size ( ) ; if ( ( p == l ) | ( r == 1 ) ) continue ; return p - l ; } return 0 ; }
OR if that row does not exist it is the last row prior to it
131,905
private void decompose ( int scalar , int [ ] decomposed ) { for ( int i = 0 ; i < decomposed . length ; i ++ ) { int avg = generator . clusteringDescendantAverages [ i ] ; decomposed [ i ] = scalar / avg ; scalar %= avg ; } for ( int i = lastRow . length - 1 ; i > 0 ; i -- ) { int avg = generator . clusteringComponent...
Translate the scalar position into a tiered position based on mean expected counts
131,906
private State seek ( int scalar ) { if ( scalar == 0 ) { this . currentRow [ 0 ] = - 1 ; clusteringComponents [ 0 ] . addFirst ( this ) ; return setHasNext ( advance ( 0 , true ) ) ; } int [ ] position = this . currentRow ; decompose ( scalar , position ) ; for ( int i = 0 ; i < position . length ; i ++ ) { if ( i != 0...
seek to the provided position to initialise the iterator
131,907
void advance ( ) { int depth = clusteringComponents . length - 1 ; long parentSeed = clusteringSeeds [ depth ] ; long rowSeed = seed ( clusteringComponents [ depth ] . peek ( ) , generator . clusteringComponents . get ( depth ) . type , parentSeed ) ; for ( int i = clusteringSeeds . length ; i < row . row . length ; i ...
to move the iterator to the next item
131,908
void fill ( int depth ) { long seed = clusteringSeeds [ depth - 1 ] ; Generator gen = generator . clusteringComponents . get ( depth ) ; gen . setSeed ( seed ) ; clusteringSeeds [ depth ] = seed ( clusteringComponents [ depth - 1 ] . peek ( ) , generator . clusteringComponents . get ( depth - 1 ) . type , seed ) ; fill...
to have been generated and their seeds populated into clusteringSeeds
131,909
void fill ( Queue < Object > queue , int count , Generator generator ) { if ( count == 1 ) { queue . add ( generator . generate ( ) ) ; return ; } switch ( this . generator . order ) { case SORTED : if ( Comparable . class . isAssignableFrom ( generator . clazz ) ) { tosort . clear ( ) ; for ( int i = 0 ; i < count ; i...
generate the clustering components into the queue
131,910
public WaitQueue . Signal requestExtraSync ( ) { WaitQueue . Signal signal = syncComplete . register ( ) ; haveWork . release ( 1 ) ; return signal ; }
Sync immediately but don t block for the sync to cmplete
131,911
static URL getStorageConfigURL ( ) throws ConfigurationException { String configUrl = System . getProperty ( "cassandra.config" ) ; if ( configUrl == null ) configUrl = DEFAULT_CONFIGURATION ; URL url ; try { url = new URL ( configUrl ) ; url . openStream ( ) . close ( ) ; } catch ( Exception e ) { ClassLoader loader =...
Inspect the classpath to find storage configuration file
131,912
public void deleteFromSchema ( Mutation mutation , long timestamp ) { ColumnFamily cf = mutation . addOrGet ( CFMetaData . SchemaColumnsCf ) ; int ldt = ( int ) ( System . currentTimeMillis ( ) / 1000 ) ; Composite prefix = CFMetaData . SchemaColumnsCf . comparator . make ( cfName , name . toString ( ) ) ; cf . addAtom...
Drop specified column from the schema using given mutation .
131,913
public static List < ColumnDefinition > fromSchema ( UntypedResultSet serializedColumns , String ksName , String cfName , AbstractType < ? > rawComparator , boolean isSuper ) { List < ColumnDefinition > cds = new ArrayList < > ( ) ; for ( UntypedResultSet . Row row : serializedColumns ) { Kind kind = row . has ( KIND )...
Deserialize columns from storage - level representation
131,914
public ByteBuffer getSerializedValue ( ByteBuffer serializedMap , ByteBuffer serializedKey , AbstractType keyType ) { try { ByteBuffer input = serializedMap . duplicate ( ) ; int n = readCollectionSize ( input , Server . VERSION_3 ) ; for ( int i = 0 ; i < n ; i ++ ) { ByteBuffer kbb = readValue ( input , Server . VERS...
Given a serialized map gets the value associated with a given key .
131,915
public static < V > Object [ ] build ( Iterable < V > source , int size , Comparator < V > comparator , boolean sorted , UpdateFunction < V > updateF ) { if ( size < FAN_FACTOR ) { V [ ] values = ( V [ ] ) new Object [ size + ( size & 1 ) ] ; { int i = 0 ; for ( V v : source ) values [ i ++ ] = v ; } if ( ! sorted ) Ar...
Creates a BTree containing all of the objects in the provided collection
131,916
public static < V > Cursor < V , V > slice ( Object [ ] btree , boolean forwards ) { Cursor < V , V > r = new Cursor < > ( ) ; r . reset ( btree , forwards ) ; return r ; }
Returns an Iterator over the entire tree
131,917
public static < K , V extends K > Cursor < K , V > slice ( Object [ ] btree , Comparator < K > comparator , K start , boolean startInclusive , K end , boolean endInclusive , boolean forwards ) { Cursor < K , V > r = new Cursor < > ( ) ; r . reset ( btree , comparator , start , startInclusive , end , endInclusive , forw...
Returns an Iterator over a sub - range of the tree
131,918
static int getLeafKeyEnd ( Object [ ] node ) { int len = node . length ; if ( len == 0 ) return 0 ; else if ( node [ len - 1 ] == null ) return len - 1 ; else return len ; }
get the last index that is non - null in the leaf node
131,919
private static < V > Collection < V > sorted ( Iterable < V > source , Comparator < V > comparator , int size ) { V [ ] vs = ( V [ ] ) new Object [ size ] ; int i = 0 ; for ( V v : source ) vs [ i ++ ] = v ; Arrays . sort ( vs , comparator ) ; return Arrays . asList ( vs ) ; }
return a sorted collection
131,920
public int completed ( InetAddress request ) { String dc = DatabaseDescriptor . getEndpointSnitch ( ) . getDatacenter ( request ) ; Queue < InetAddress > requests = requestsByDatacenter . get ( dc ) ; assert requests != null ; assert request . equals ( requests . peek ( ) ) ; requests . poll ( ) ; if ( ! requests . isE...
Returns how many request remains
131,921
public static DataResource fromName ( String name ) { String [ ] parts = StringUtils . split ( name , '/' ) ; if ( ! parts [ 0 ] . equals ( ROOT_NAME ) || parts . length > 3 ) throw new IllegalArgumentException ( String . format ( "%s is not a valid data resource name" , name ) ) ; if ( parts . length == 1 ) return roo...
Parses a data resource name into a DataResource instance .
131,922
protected < T extends Number > Gauge < T > createColumnFamilyGauge ( final String name , Gauge < T > gauge ) { return createColumnFamilyGauge ( name , gauge , new Gauge < Long > ( ) { public Long value ( ) { long total = 0 ; for ( Metric cfGauge : allColumnFamilyMetrics . get ( name ) ) { total = total + ( ( Gauge < ? ...
Create a gauge that will be part of a merged version of all column families . The global gauge will merge each CF gauge by adding their values
131,923
protected < G , T > Gauge < T > createColumnFamilyGauge ( String name , Gauge < T > gauge , Gauge < G > globalGauge ) { Gauge < T > cfGauge = Metrics . newGauge ( factory . createMetricName ( name ) , gauge ) ; if ( register ( name , cfGauge ) ) { Metrics . newGauge ( globalNameFactory . createMetricName ( name ) , glo...
Create a gauge that will be part of a merged version of all column families . The global gauge is defined as the globalGauge parameter
131,924
protected Counter createColumnFamilyCounter ( final String name ) { Counter cfCounter = Metrics . newCounter ( factory . createMetricName ( name ) ) ; if ( register ( name , cfCounter ) ) { Metrics . newGauge ( globalNameFactory . createMetricName ( name ) , new Gauge < Long > ( ) { public Long value ( ) { long total =...
Creates a counter that will also have a global counter thats the sum of all counters across different column families
131,925
protected ColumnFamilyHistogram createColumnFamilyHistogram ( String name , Histogram keyspaceHistogram ) { Histogram cfHistogram = Metrics . newHistogram ( factory . createMetricName ( name ) , true ) ; register ( name , cfHistogram ) ; return new ColumnFamilyHistogram ( cfHistogram , keyspaceHistogram , Metrics . new...
Create a histogram - like interface that will register both a CF keyspace and global level histogram and forward any updates to both
131,926
private boolean register ( String name , Metric metric ) { boolean ret = allColumnFamilyMetrics . putIfAbsent ( name , new HashSet < Metric > ( ) ) == null ; allColumnFamilyMetrics . get ( name ) . add ( metric ) ; all . add ( name ) ; return ret ; }
Registers a metric to be removed when unloading CF .
131,927
public static void setOutputKeyspace ( Configuration conf , String keyspace ) { if ( keyspace == null ) throw new UnsupportedOperationException ( "keyspace may not be null" ) ; conf . set ( OUTPUT_KEYSPACE_CONFIG , keyspace ) ; }
Set the keyspace for the output of this job .
131,928
public static void setOutputColumnFamily ( Configuration conf , String keyspace , String columnFamily ) { setOutputKeyspace ( conf , keyspace ) ; setOutputColumnFamily ( conf , columnFamily ) ; }
Set the column family for the output of this job .
131,929
public static void setInputSlicePredicate ( Configuration conf , SlicePredicate predicate ) { conf . set ( INPUT_PREDICATE_CONFIG , thriftToString ( predicate ) ) ; }
Set the predicate that determines what columns will be selected from each row .
131,930
public static KeyRange getInputKeyRange ( Configuration conf ) { String str = conf . get ( INPUT_KEYRANGE_CONFIG ) ; return str == null ? null : keyRangeFromString ( str ) ; }
may be null if unset
131,931
public OnDiskAtom readNext ( ) throws IOException { Composite name = nameDeserializer . readNext ( ) ; assert ! name . isEmpty ( ) ; nextFlags = nextFlags == Integer . MIN_VALUE ? in . readUnsignedByte ( ) : nextFlags ; OnDiskAtom atom = ( nextFlags & ColumnSerializer . RANGE_TOMBSTONE_MASK ) != 0 ? type . rangeTombsto...
Returns the next atom .
131,932
public void skipNext ( ) throws IOException { nameDeserializer . skipNext ( ) ; nextFlags = nextFlags == Integer . MIN_VALUE ? in . readUnsignedByte ( ) : nextFlags ; if ( ( nextFlags & ColumnSerializer . RANGE_TOMBSTONE_MASK ) != 0 ) type . rangeTombstoneSerializer ( ) . skipBody ( in , version ) ; else type . columnS...
Skips the next atom .
131,933
public void connectionComplete ( SocketAddress socket ) { assert socket != null ; activeSocketSessions . remove ( socket ) ; if ( logger . isTraceEnabled ( ) ) logger . trace ( "ClientState removed for socket addr {}" , socket ) ; }
The connection associated with
131,934
public void delete ( final DecoratedKey partitionKey ) { if ( indexQueue == null ) { deleteInner ( partitionKey ) ; } else { indexQueue . submitAsynchronous ( partitionKey , new Runnable ( ) { public void run ( ) { deleteInner ( partitionKey ) ; } } ) ; } }
Deletes the partition identified by the specified partition key . This operation is performed asynchronously .
131,935
public final void commit ( ) { if ( indexQueue == null ) { luceneIndex . commit ( ) ; } else { indexQueue . submitSynchronous ( new Runnable ( ) { public void run ( ) { luceneIndex . commit ( ) ; } } ) ; } }
Commits the pending changes . This operation is performed asynchronously .
131,936
public static void printOptions ( PrintStream out , String command , GroupedOptions ... groupings ) { out . println ( ) ; boolean firstRow = true ; for ( GroupedOptions grouping : groupings ) { if ( ! firstRow ) { out . println ( " OR " ) ; } firstRow = false ; StringBuilder sb = new StringBuilder ( "Usage: " + command...
pretty prints all of the option groupings
131,937
public ByteBuffer createMessage ( boolean compress , int version ) { int header = 0 ; if ( compress ) header |= 4 ; header |= 8 ; header |= ( version << 8 ) ; byte [ ] bytes ; try { int size = ( int ) StreamInitMessage . serializer . serializedSize ( this , version ) ; DataOutputBuffer buffer = new DataOutputBuffer ( s...
Create serialized message .
131,938
public RowIndexEntry tryAppend ( AbstractCompactedRow row ) { writer . mark ( ) ; try { return append ( row ) ; } catch ( Throwable t ) { writer . resetAndTruncate ( ) ; throw t ; } }
attempts to append the row if fails resets the writer position
131,939
private void moveStarts ( SSTableReader newReader , DecoratedKey lowerbound , boolean reset ) { if ( isOffline ) return ; List < SSTableReader > toReplace = new ArrayList < > ( ) ; List < SSTableReader > replaceWith = new ArrayList < > ( ) ; final List < DecoratedKey > invalidateKeys = new ArrayList < > ( ) ; if ( ! re...
Replace the readers we are rewriting with cloneWithNewStart reclaiming any page cache that is no longer needed and transferring any key cache entries over to the new reader expiring them from the old . if reset is true we are instead restoring the starts of the readers from before the rewriting began
131,940
private void replaceWithFinishedReaders ( List < SSTableReader > finished ) { if ( isOffline ) { for ( SSTableReader reader : discard ) { if ( reader . getCurrentReplacement ( ) == reader ) reader . markObsolete ( ) ; reader . selfRef ( ) . release ( ) ; } } else { dataTracker . replaceEarlyOpenedFiles ( discard , fini...
cleanup all our temporary readers and swap in our new ones
131,941
public CQLSSTableWriter rawAddRow ( ByteBuffer ... values ) throws InvalidRequestException , IOException { return rawAddRow ( Arrays . asList ( values ) ) ; }
Adds a new row to the writer given already serialized values .
131,942
public static void calculatePendingRanges ( AbstractReplicationStrategy strategy , String keyspaceName ) { TokenMetadata tm = StorageService . instance . getTokenMetadata ( ) ; Multimap < Range < Token > , InetAddress > pendingRanges = HashMultimap . create ( ) ; BiMultiValMap < Token , InetAddress > bootstrapTokens = ...
public & static for testing purposes
131,943
public synchronized void gossiperStarting ( ) { gossiperInitialized = true ; StorageService . instance . gossipSnitchInfo ( ) ; Gossiper . instance . register ( new ReconnectableSnitchHelper ( this , localNodeData . datacenter , true ) ) ; }
Called in preparation for the initiation of the gossip loop .
131,944
public synchronized ScheduledFuture scheduleTimeout ( final int sequenceNumber , long time , TimeUnit unit ) { if ( ! files . containsKey ( sequenceNumber ) ) return null ; ScheduledFuture future = timeoutExecutor . schedule ( new Runnable ( ) { public void run ( ) { synchronized ( StreamTransferTask . this ) { timeout...
Schedule timeout task to release reference for file sent . When not receiving ACK after sending to receiver in given time the task will release reference .
131,945
public void add ( Composite start , Composite end , long markedAt , int delTime ) { if ( isEmpty ( ) ) { addInternal ( 0 , start , end , markedAt , delTime ) ; return ; } int c = comparator . compare ( ends [ size - 1 ] , start ) ; if ( c <= 0 ) { addInternal ( size , start , end , markedAt , delTime ) ; } else { int p...
Adds a new range tombstone .
131,946
public void purge ( int gcBefore ) { int j = 0 ; for ( int i = 0 ; i < size ; i ++ ) { if ( delTimes [ i ] >= gcBefore ) setInternal ( j ++ , starts [ i ] , ends [ i ] , markedAts [ i ] , delTimes [ i ] ) ; } size = j ; }
Removes all range tombstones whose local deletion time is older than gcBefore .
131,947
public void updateDigest ( MessageDigest digest ) { ByteBuffer longBuffer = ByteBuffer . allocate ( 8 ) ; for ( int i = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < starts [ i ] . size ( ) ; j ++ ) digest . update ( starts [ i ] . get ( j ) . duplicate ( ) ) ; for ( int j = 0 ; j < ends [ i ] . size ( ) ; j ++ ) diges...
Calculates digest for triggering read repair on mismatch
131,948
public long [ ] getHashBuckets ( ByteBuffer key , int hashCount , long max ) { long [ ] hash = new long [ 2 ] ; hash ( key , key . position ( ) , key . remaining ( ) , 0L , hash ) ; long [ ] indexes = new long [ hashCount ] ; setIndexes ( hash [ 0 ] , hash [ 1 ] , hashCount , max , indexes ) ; return indexes ; }
rather than using the threadLocal like we do in production
131,949
private long [ ] indexes ( ByteBuffer key ) { long [ ] indexes = reusableIndexes . get ( ) ; hash ( key , key . position ( ) , key . remaining ( ) , 0L , indexes ) ; setIndexes ( indexes [ 0 ] , indexes [ 1 ] , hashCount , bitset . capacity ( ) , indexes ) ; return indexes ; }
a second threadlocal lookup .
131,950
public final void addFields ( Document document , CellName cellName ) { String serializedKey = ByteBufferUtils . toString ( cellName . toByteBuffer ( ) ) ; Field field = new StringField ( FIELD_NAME , serializedKey , Field . Store . YES ) ; document . add ( field ) ; }
Adds to the specified document the clustering key contained in the specified cell name .
131,951
public final List < CellName > clusteringKeys ( ColumnFamily columnFamily ) { List < CellName > clusteringKeys = new ArrayList < > ( ) ; CellName lastClusteringKey = null ; for ( Cell cell : columnFamily ) { CellName cellName = cell . name ( ) ; if ( ! isStatic ( cellName ) ) { CellName clusteringKey = extractClusterin...
Returns the common clustering keys of the specified column family .
131,952
public final CellName makeCellName ( CellName cellName , ColumnDefinition columnDefinition ) { return cellNameType . create ( start ( cellName ) , columnDefinition ) ; }
Returns the storage engine column name for the specified column identifier using the specified clustering key .
131,953
public final CellName clusteringKey ( BytesRef bytesRef ) { String string = bytesRef . utf8ToString ( ) ; ByteBuffer bb = ByteBufferUtils . fromString ( string ) ; return cellNameType . cellFromByteBuffer ( bb ) ; }
Returns the clustering key contained in the specified Lucene field value .
131,954
public final Composite start ( CellName cellName ) { CBuilder builder = cellNameType . builder ( ) ; for ( int i = 0 ; i < cellName . clusteringSize ( ) ; i ++ ) { ByteBuffer component = cellName . get ( i ) ; builder . add ( component ) ; } return builder . build ( ) ; }
Returns the first possible cell name of those having the same clustering key that the specified cell name .
131,955
public final Composite end ( CellName cellName ) { return start ( cellName ) . withEOC ( Composite . EOC . END ) ; }
Returns the last possible cell name of those having the same clustering key that the specified cell name .
131,956
public final List < CellName > sort ( List < CellName > clusteringKeys ) { List < CellName > result = new ArrayList < > ( clusteringKeys ) ; Collections . sort ( result , new Comparator < CellName > ( ) { public int compare ( CellName o1 , CellName o2 ) { return cellNameType . compare ( o1 , o2 ) ; } } ) ; return resul...
Returns the specified list of clustering keys sorted according to the table cell name comparator .
131,957
public String get ( String propertyName , String defaultValue ) { return properties . getProperty ( propertyName , defaultValue ) ; }
Get a snitch property value or return defaultValue if not defined .
131,958
public static AbstractType < ? > parse ( String str ) throws SyntaxException , ConfigurationException { if ( str == null ) return BytesType . instance ; AbstractType < ? > type = cache . get ( str ) ; if ( type != null ) return type ; int i = 0 ; i = skipBlank ( str , i ) ; int j = i ; while ( ! isEOS ( str , i ) && is...
Parse a string containing an type definition .
131,959
public AbstractType < ? > parse ( ) throws SyntaxException , ConfigurationException { skipBlank ( ) ; String name = readNextIdentifier ( ) ; skipBlank ( ) ; if ( ! isEOS ( ) && str . charAt ( idx ) == '(' ) return getAbstractType ( name , this ) ; else return getAbstractType ( name ) ; }
Parse an AbstractType from current position of this parser .
131,960
private boolean skipBlankAndComma ( ) { boolean commaFound = false ; while ( ! isEOS ( ) ) { int c = str . charAt ( idx ) ; if ( c == ',' ) { if ( commaFound ) return true ; else commaFound = true ; } else if ( ! isBlank ( c ) ) { return true ; } ++ idx ; } return false ; }
skip all blank and at best one comma return true if there not EOS
131,961
public String readNextIdentifier ( ) { int i = idx ; while ( ! isEOS ( ) && isIdentifierChar ( str . charAt ( idx ) ) ) ++ idx ; return str . substring ( i , idx ) ; }
left idx positioned on the character stopping the read
131,962
private void seekToChunkStart ( ) { if ( getOnDiskFilePointer ( ) != chunkOffset ) { try { out . seek ( chunkOffset ) ; } catch ( IOException e ) { throw new FSReadError ( e , getPath ( ) ) ; } } }
Seek to the offset where next compressed data chunk should be stored .
131,963
public void validate ( CFMetaData metadata ) { for ( Map . Entry < String , ColumnMapper > entry : columnMappers . entrySet ( ) ) { String name = entry . getKey ( ) ; ColumnMapper columnMapper = entry . getValue ( ) ; ByteBuffer columnName = UTF8Type . instance . decompose ( name ) ; ColumnDefinition columnDefinition =...
Checks if this is consistent with the specified column family metadata .
131,964
public void reload ( ) { Collection < ByteBuffer > indexedColumnNames = indexesByColumn . keySet ( ) ; for ( ByteBuffer indexedColumn : indexedColumnNames ) { ColumnDefinition def = baseCfs . metadata . getColumnDefinition ( indexedColumn ) ; if ( def == null || def . getIndexType ( ) == null ) removeIndexedColumn ( in...
Drops and adds new indexes associated with the underlying CF
131,965
public void maybeBuildSecondaryIndexes ( Collection < SSTableReader > sstables , Set < String > idxNames ) { if ( idxNames . isEmpty ( ) ) return ; logger . info ( String . format ( "Submitting index build of %s for data in %s" , idxNames , StringUtils . join ( sstables , ", " ) ) ) ; SecondaryIndexBuilder builder = ne...
Does a full blocking rebuild of the indexes specified by columns from the sstables . Does nothing if columns is empty .
131,966
public void removeIndexedColumn ( ByteBuffer column ) { SecondaryIndex index = indexesByColumn . remove ( column ) ; if ( index == null ) return ; if ( index instanceof PerRowSecondaryIndex ) { index . removeColumnDef ( column ) ; if ( index . getColumnDefs ( ) . isEmpty ( ) ) { allIndexes . remove ( index ) ; rowLevel...
Removes a existing index
131,967
public synchronized Future < ? > addIndexedColumn ( ColumnDefinition cdef ) { if ( indexesByColumn . containsKey ( cdef . name . bytes ) ) return null ; assert cdef . getIndexType ( ) != null ; SecondaryIndex index ; try { index = SecondaryIndex . createInstance ( baseCfs , cdef ) ; } catch ( ConfigurationException e )...
Adds and builds a index for a column
131,968
public void flushIndexesBlocking ( ) { List < Future < ? > > wait = new ArrayList < > ( ) ; synchronized ( baseCfs . getDataTracker ( ) ) { for ( SecondaryIndex index : allIndexes ) if ( index . getIndexCfs ( ) != null ) wait . add ( index . getIndexCfs ( ) . forceFlush ( ) ) ; } for ( SecondaryIndex index : allIndexes...
Flush all indexes to disk
131,969
public void indexRow ( ByteBuffer key , ColumnFamily cf , OpOrder . Group opGroup ) { Set < Class < ? extends SecondaryIndex > > appliedRowLevelIndexes = null ; for ( SecondaryIndex index : allIndexes ) { if ( index instanceof PerRowSecondaryIndex ) { if ( appliedRowLevelIndexes == null ) appliedRowLevelIndexes = new H...
When building an index against existing data add the given row to the index
131,970
public void deleteFromIndexes ( DecoratedKey key , List < Cell > indexedColumnsInRow , OpOrder . Group opGroup ) { Set < Class < ? extends SecondaryIndex > > cleanedRowLevelIndexes = null ; for ( Cell cell : indexedColumnsInRow ) { for ( SecondaryIndex index : indexFor ( cell . name ( ) ) ) { if ( index instanceof PerR...
Delete all columns from all indexes for this row . For when cleanup rips a row out entirely .
131,971
public List < SecondaryIndexSearcher > getIndexSearchersForQuery ( List < IndexExpression > clause ) { Map < String , Set < ByteBuffer > > groupByIndexType = new HashMap < > ( ) ; for ( IndexExpression ix : clause ) { SecondaryIndex index = getIndexForColumn ( ix . column ) ; if ( index == null || ! index . supportsOpe...
Get a list of IndexSearchers from the union of expression index types
131,972
public List < Row > search ( ExtendedFilter filter ) { SecondaryIndexSearcher mostSelective = getHighestSelectivityIndexSearcher ( filter . getClause ( ) ) ; if ( mostSelective == null ) return Collections . emptyList ( ) ; else return mostSelective . search ( filter ) ; }
Performs a search across a number of column indexes
131,973
public void write ( DataOutput out ) throws IOException { out . writeUTF ( startToken ) ; out . writeUTF ( endToken ) ; out . writeInt ( dataNodes . length ) ; for ( String endpoint : dataNodes ) { out . writeUTF ( endpoint ) ; } }
KeyspaceSplits as needed by the Writable interface .
131,974
public void afterExecute ( Runnable r , Throwable t ) { super . afterExecute ( r , t ) ; DebuggableThreadPoolExecutor . logExceptionsAfterExecute ( r , t ) ; }
We need this as well as the wrapper for the benefit of non - repeating tasks
131,975
public long snapshotCreationTime ( String snapshotName ) { for ( File dir : dataPaths ) { File snapshotDir = new File ( dir , join ( SNAPSHOT_SUBDIR , snapshotName ) ) ; if ( snapshotDir . exists ( ) ) return snapshotDir . lastModified ( ) ; } throw new RuntimeException ( "Snapshot " + snapshotName + " doesn't exist" )...
The snapshot must exist
131,976
public static List < File > getKSChildDirectories ( String ksName ) { List < File > result = new ArrayList < > ( ) ; for ( DataDirectory dataDirectory : dataDirectories ) { File ksDir = new File ( dataDirectory . location , ksName ) ; File [ ] cfDirs = ksDir . listFiles ( ) ; if ( cfDirs == null ) continue ; for ( File...
Recursively finds all the sub directories in the KS directory .
131,977
protected static String makeFilename ( File directory , final String keyspace , final String columnFamily ) { final Set < Descriptor > existing = new HashSet < Descriptor > ( ) ; directory . list ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { Pair < Descriptor , Component > p = SSTable . ...
find available generation and pick up filename from that
131,978
private void setToRowStart ( RowIndexEntry rowEntry , FileDataInput in ) throws IOException { if ( in == null ) { this . file = sstable . getFileDataInput ( rowEntry . position ) ; } else { this . file = in ; in . seek ( rowEntry . position ) ; } sstable . partitioner . decorateKey ( ByteBufferUtil . readWithShortLengt...
Sets the seek position to the start of the row for column scanning .
131,979
public void collectMarkerSpecification ( VariableSpecifications boundNames ) { if ( collectionElement != null ) collectionElement . collectMarkerSpecification ( boundNames ) ; if ( operator . equals ( Operator . IN ) && inValues != null ) { for ( Term value : inValues ) value . collectMarkerSpecification ( boundNames )...
Collects the column specification for the bind variables of this operation .
131,980
public Socket createConnection ( InetAddress peer ) throws IOException { int attempts = 0 ; while ( true ) { try { Socket socket = OutboundTcpConnectionPool . newSocket ( peer ) ; socket . setSoTimeout ( DatabaseDescriptor . getStreamingSocketTimeout ( ) ) ; socket . setKeepAlive ( true ) ; return socket ; } catch ( IO...
Connect to peer and start exchanging message . When connect attempt fails this retries for maximum of MAX_CONNECT_ATTEMPTS times .
131,981
public void init ( ) { byte sizedepth = ( byte ) ( Math . log10 ( maxsize ) / Math . log10 ( 2 ) ) ; byte depth = ( byte ) Math . min ( sizedepth , hashdepth ) ; root = initHelper ( fullRange . left , fullRange . right , ( byte ) 0 , depth ) ; size = ( long ) Math . pow ( 2 , depth ) ; }
Initializes this tree by splitting it until hashdepth is reached or until an additional level of splits would violate maxsize .
131,982
public TreeRange get ( Token t ) { return getHelper ( root , fullRange . left , fullRange . right , ( byte ) 0 , t ) ; }
For testing purposes . Gets the smallest range containing the token .
131,983
public boolean split ( Token t ) { if ( ! ( size < maxsize ) ) return false ; try { root = splitHelper ( root , fullRange . left , fullRange . right , ( byte ) 0 , t ) ; } catch ( StopRecursion . TooDeep e ) { return false ; } return true ; }
Splits the range containing the given token if no tree limits would be violated . If the range would be split to a depth below hashdepth or if the tree already contains maxsize subranges this operation will fail .
131,984
public static void inspectThrowable ( Throwable t ) { boolean isUnstable = false ; if ( t instanceof OutOfMemoryError ) isUnstable = true ; if ( DatabaseDescriptor . getDiskFailurePolicy ( ) == Config . DiskFailurePolicy . die ) if ( t instanceof FSError || t instanceof CorruptSSTableException ) isUnstable = true ; if ...
Certain Throwables and Exceptions represent Die conditions for the server .
131,985
private void reduceNameFilter ( QueryFilter filter , ColumnFamily container , long sstableTimestamp ) { if ( container == null ) return ; for ( Iterator < CellName > iterator = ( ( NamesQueryFilter ) filter . filter ) . columns . iterator ( ) ; iterator . hasNext ( ) ; ) { CellName filterColumn = iterator . next ( ) ; ...
remove columns from
131,986
public static CellNameType getIndexComparator ( CFMetaData baseMetadata , ColumnDefinition cfDef ) { if ( cfDef . type . isCollection ( ) && cfDef . type . isMultiCell ( ) ) { switch ( ( ( CollectionType ) cfDef . type ) . kind ) { case LIST : return CompositesIndexOnCollectionValue . buildIndexComparator ( baseMetadat...
Check SecondaryIndex . getIndexComparator if you want to know why this is static
131,987
private String getLocation ( ) { Collection < InetAddress > localAddresses = FBUtilities . getAllLocalAddresses ( ) ; for ( InetAddress address : localAddresses ) { for ( String location : split . getLocations ( ) ) { InetAddress locationAddress = null ; try { locationAddress = InetAddress . getByName ( location ) ; } ...
not necessarily on Cassandra machines too . This should be adequate for single - DC clusters at least .
131,988
public static RuntimeException rethrow ( RequestExecutionException e ) throws UnavailableException , TimedOutException { if ( e instanceof RequestTimeoutException ) throw toThrift ( ( RequestTimeoutException ) e ) ; else throw new UnavailableException ( ) ; }
for methods that have a return value .
131,989
OutboundTcpConnection getConnection ( MessageOut msg ) { Stage stage = msg . getStage ( ) ; return stage == Stage . REQUEST_RESPONSE || stage == Stage . INTERNAL_RESPONSE || stage == Stage . GOSSIP ? ackCon : cmdCon ; }
returns the appropriate connection based on message type . returns null if a connection could not be established .
131,990
public void execute ( Runnable task ) { tasksInProcess . incrementAndGet ( ) ; try { super . execute ( task ) ; } catch ( RuntimeException e ) { tasksInProcess . decrementAndGet ( ) ; throw e ; } catch ( Error e ) { tasksInProcess . decrementAndGet ( ) ; throw e ; } }
Before calling super s version of this method the amount of tasks which are currently in process is first incremented .
131,991
public static int getEffectiveIndexIntervalAfterIndex ( int index , int samplingLevel , int minIndexInterval ) { assert index >= 0 ; index %= samplingLevel ; List < Integer > originalIndexes = getOriginalIndexes ( samplingLevel ) ; int nextEntryOriginalIndex = ( index == originalIndexes . size ( ) - 1 ) ? BASE_SAMPLING...
Calculates the effective index interval after the entry at index in an IndexSummary . In other words this returns the number of partitions in the primary on - disk index before the next partition that has an entry in the index summary . If samplingLevel == BASE_SAMPLING_LEVEL this will be equal to the index interval .
131,992
Allocation allocate ( Mutation mutation , int size ) { final OpOrder . Group opGroup = appendOrder . start ( ) ; try { int position = allocate ( size ) ; if ( position < 0 ) { opGroup . close ( ) ; return null ; } markDirty ( mutation , position ) ; return new Allocation ( this , opGroup , position , ( ByteBuffer ) buf...
Allocate space in this buffer for the provided mutation and return the allocated Allocation object . Returns null if there is not enough space in this segment and a new segment is needed .
131,993
private int allocate ( int size ) { while ( true ) { int prev = allocatePosition . get ( ) ; int next = prev + size ; if ( next >= buffer . capacity ( ) ) return - 1 ; if ( allocatePosition . compareAndSet ( prev , next ) ) return prev ; } }
allocate bytes in the segment or return - 1 if not enough space
131,994
void discardUnusedTail ( ) { try ( OpOrder . Group group = appendOrder . start ( ) ) { while ( true ) { int prev = allocatePosition . get ( ) ; int next = buffer . capacity ( ) + 1 ; if ( prev == next ) return ; if ( allocatePosition . compareAndSet ( prev , next ) ) { discardedTailFrom = prev ; return ; } } } }
ensures no more of this segment is writeable by allocating any unused section at the end and marking it discarded
131,995
synchronized void sync ( ) { try { if ( allocatePosition . get ( ) <= lastSyncedOffset + SYNC_MARKER_SIZE ) return ; int nextMarker ; nextMarker = allocate ( SYNC_MARKER_SIZE ) ; boolean close = false ; if ( nextMarker < 0 ) { discardUnusedTail ( ) ; close = true ; waitForModifications ( ) ; if ( discardedTailFrom < bu...
Forces a disk flush for this segment file .
131,996
CommitLogSegment recycle ( ) { try { sync ( ) ; } catch ( FSWriteError e ) { logger . error ( "I/O error flushing {} {}" , this , e . getMessage ( ) ) ; throw e ; } close ( ) ; return new CommitLogSegment ( getPath ( ) ) ; }
Recycle processes an unneeded segment file for reuse .
131,997
public synchronized void markClean ( UUID cfId , ReplayPosition context ) { if ( ! cfDirty . containsKey ( cfId ) ) return ; if ( context . segment == id ) markClean ( cfId , context . position ) ; else if ( context . segment > id ) markClean ( cfId , Integer . MAX_VALUE ) ; }
Marks the ColumnFamily specified by cfId as clean for this log segment . If the given context argument is contained in this file it will only mark the CF as clean if no newer writes have taken place .
131,998
public String dirtyString ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( UUID cfId : getDirtyCFIDs ( ) ) { CFMetaData m = Schema . instance . getCFMetaData ( cfId ) ; sb . append ( m == null ? "<deleted>" : m . cfName ) . append ( " (" ) . append ( cfId ) . append ( "), " ) ; } return sb . toString ( ) ; }
For debugging not fast
131,999
public StreamPlan transferFiles ( InetAddress to , Collection < StreamSession . SSTableStreamingSections > sstableDetails ) { coordinator . transferFiles ( to , sstableDetails ) ; return this ; }
Add transfer task to send given SSTable files .