idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
12,100 | public boolean releaseIfHolds ( T referenced ) { Ref ref = references . remove ( referenced ) ; if ( ref != null ) ref . release ( ) ; return ref != null ; } | Release the retained Ref to the provided object if held return false otherwise |
12,101 | public void release ( Collection < T > release ) { List < Ref < T > > refs = new ArrayList < > ( ) ; List < T > notPresent = null ; for ( T obj : release ) { Ref < T > ref = references . remove ( obj ) ; if ( ref == null ) { if ( notPresent == null ) notPresent = new ArrayList < > ( ) ; notPresent . add ( obj ) ; } else { refs . add ( ref ) ; } } IllegalStateException notPresentFail = null ; if ( notPresent != null ) { notPresentFail = new IllegalStateException ( "Could not release references to " + notPresent + " as references to these objects were not held" ) ; notPresentFail . fillInStackTrace ( ) ; } try { release ( refs ) ; } catch ( Throwable t ) { if ( notPresentFail != null ) t . addSuppressed ( notPresentFail ) ; } if ( notPresentFail != null ) throw notPresentFail ; } | Release a retained Ref to all of the provided objects ; if any is not held an exception will be thrown |
12,102 | public boolean tryRef ( T t ) { Ref < T > ref = t . tryRef ( ) ; if ( ref == null ) return false ; ref = references . put ( t , ref ) ; if ( ref != null ) ref . release ( ) ; return true ; } | Attempt to take a reference to the provided object ; if it has already been released null will be returned |
12,103 | public Refs < T > addAll ( Refs < T > add ) { List < Ref < T > > overlap = new ArrayList < > ( ) ; for ( Map . Entry < T , Ref < T > > e : add . references . entrySet ( ) ) { if ( this . references . containsKey ( e . getKey ( ) ) ) overlap . add ( e . getValue ( ) ) ; else this . references . put ( e . getKey ( ) , e . getValue ( ) ) ; } add . references . clear ( ) ; release ( overlap ) ; return this ; } | Merge two sets of references ensuring only one reference is retained between the two sets |
12,104 | public static < T extends RefCounted < T > > Refs < T > tryRef ( Iterable < T > reference ) { HashMap < T , Ref < T > > refs = new HashMap < > ( ) ; for ( T rc : reference ) { Ref < T > ref = rc . tryRef ( ) ; if ( ref == null ) { release ( refs . values ( ) ) ; return null ; } refs . put ( rc , ref ) ; } return new Refs < T > ( refs ) ; } | Acquire a reference to all of the provided objects or none |
12,105 | public Allocation allocate ( Mutation mutation , int size ) { CommitLogSegment segment = allocatingFrom ( ) ; Allocation alloc ; while ( null == ( alloc = segment . allocate ( mutation , size ) ) ) { advanceAllocatingFrom ( segment ) ; segment = allocatingFrom ; } return alloc ; } | Reserve space in the current segment for the provided mutation or if there isn t space available create a new segment . |
12,106 | CommitLogSegment allocatingFrom ( ) { CommitLogSegment r = allocatingFrom ; if ( r == null ) { advanceAllocatingFrom ( null ) ; r = allocatingFrom ; } return r ; } | simple wrapper to ensure non - null value for allocatingFrom ; only necessary on first call |
12,107 | private void advanceAllocatingFrom ( CommitLogSegment old ) { while ( true ) { CommitLogSegment next ; synchronized ( this ) { if ( allocatingFrom != old ) return ; next = availableSegments . poll ( ) ; if ( next != null ) { allocatingFrom = next ; activeSegments . add ( next ) ; } } if ( next != null ) { if ( old != null ) { CommitLog . instance . archiver . maybeArchive ( old ) ; old . discardUnusedTail ( ) ; } CommitLog . instance . requestExtraSync ( ) ; return ; } WaitQueue . Signal signal = hasAvailableSegments . register ( CommitLog . instance . metrics . waitingOnSegmentAllocation . time ( ) ) ; wakeManager ( ) ; if ( ! availableSegments . isEmpty ( ) || allocatingFrom != old ) { signal . cancel ( ) ; if ( allocatingFrom != old ) return ; continue ; } signal . awaitUninterruptibly ( ) ; } } | Fetches a new segment from the queue creating a new one if necessary and activates it |
12,108 | void forceRecycleAll ( Iterable < UUID > droppedCfs ) { List < CommitLogSegment > segmentsToRecycle = new ArrayList < > ( activeSegments ) ; CommitLogSegment last = segmentsToRecycle . get ( segmentsToRecycle . size ( ) - 1 ) ; advanceAllocatingFrom ( last ) ; last . waitForModifications ( ) ; Set < Keyspace > keyspaces = new HashSet < > ( ) ; for ( UUID cfId : last . getDirtyCFIDs ( ) ) { ColumnFamilyStore cfs = Schema . instance . getColumnFamilyStoreInstance ( cfId ) ; if ( cfs != null ) keyspaces . add ( cfs . keyspace ) ; } for ( Keyspace keyspace : keyspaces ) keyspace . writeOrder . awaitNewBarrier ( ) ; Future < ? > future = flushDataFrom ( segmentsToRecycle , true ) ; try { future . get ( ) ; for ( CommitLogSegment segment : activeSegments ) for ( UUID cfId : droppedCfs ) segment . markClean ( cfId , segment . getContext ( ) ) ; for ( CommitLogSegment segment : activeSegments ) if ( segment . isUnused ( ) ) recycleSegment ( segment ) ; CommitLogSegment first ; if ( ( first = activeSegments . peek ( ) ) != null && first . id <= last . id ) logger . error ( "Failed to force-recycle all segments; at least one segment is still in use with dirty CFs." ) ; } catch ( Throwable t ) { logger . error ( "Failed waiting for a forced recycle of in-use commit log segments" , t ) ; } } | Switch to a new segment regardless of how much is left in the current one . |
12,109 | void recycleSegment ( final CommitLogSegment segment ) { boolean archiveSuccess = CommitLog . instance . archiver . maybeWaitForArchiving ( segment . getName ( ) ) ; activeSegments . remove ( segment ) ; if ( ! archiveSuccess ) { discardSegment ( segment , false ) ; return ; } if ( isCapExceeded ( ) ) { discardSegment ( segment , true ) ; return ; } logger . debug ( "Recycling {}" , segment ) ; segmentManagementTasks . add ( new Callable < CommitLogSegment > ( ) { public CommitLogSegment call ( ) { return segment . recycle ( ) ; } } ) ; } | Indicates that a segment is no longer in use and that it should be recycled . |
12,110 | void recycleSegment ( final File file ) { if ( isCapExceeded ( ) || CommitLogDescriptor . fromFileName ( file . getName ( ) ) . getMessagingVersion ( ) != MessagingService . current_version ) { logger . debug ( "(Unopened) segment {} is no longer needed and will be deleted now" , file ) ; FileUtils . deleteWithConfirm ( file ) ; return ; } logger . debug ( "Recycling {}" , file ) ; size . addAndGet ( DatabaseDescriptor . getCommitLogSegmentSize ( ) ) ; segmentManagementTasks . add ( new Callable < CommitLogSegment > ( ) { public CommitLogSegment call ( ) { return new CommitLogSegment ( file . getPath ( ) ) ; } } ) ; } | Differs from the above because it can work on any file instead of just existing commit log segments managed by this manager . |
12,111 | private void discardSegment ( final CommitLogSegment segment , final boolean deleteFile ) { logger . debug ( "Segment {} is no longer active and will be deleted {}" , segment , deleteFile ? "now" : "by the archive script" ) ; size . addAndGet ( - DatabaseDescriptor . getCommitLogSegmentSize ( ) ) ; segmentManagementTasks . add ( new Callable < CommitLogSegment > ( ) { public CommitLogSegment call ( ) { segment . close ( ) ; if ( deleteFile ) segment . delete ( ) ; return null ; } } ) ; } | Indicates that a segment file should be deleted . |
12,112 | public void resetUnsafe ( ) { logger . debug ( "Closing and clearing existing commit log segments..." ) ; while ( ! segmentManagementTasks . isEmpty ( ) ) Thread . yield ( ) ; for ( CommitLogSegment segment : activeSegments ) segment . close ( ) ; activeSegments . clear ( ) ; for ( CommitLogSegment segment : availableSegments ) segment . close ( ) ; availableSegments . clear ( ) ; allocatingFrom = null ; } | Resets all the segments for testing purposes . DO NOT USE THIS OUTSIDE OF TESTS . |
12,113 | public static BloomSpecification computeBloomSpec ( int bucketsPerElement ) { assert bucketsPerElement >= 1 ; assert bucketsPerElement <= probs . length - 1 ; return new BloomSpecification ( optKPerBuckets [ bucketsPerElement ] , bucketsPerElement ) ; } | Given the number of buckets that can be used per element return a specification that minimizes the false positive rate . |
12,114 | public static int maxBucketsPerElement ( long numElements ) { numElements = Math . max ( 1 , numElements ) ; double v = ( Long . MAX_VALUE - EXCESS ) / ( double ) numElements ; if ( v < 1.0 ) { throw new UnsupportedOperationException ( "Cannot compute probabilities for " + numElements + " elements." ) ; } return Math . min ( BloomCalculations . probs . length - 1 , ( int ) v ) ; } | Calculates the maximum number of buckets per element that this implementation can support . Crucially it will lower the bucket count if necessary to meet BitSet s size restrictions . |
12,115 | public Boolean getBoolean ( String key , Boolean defaultValue ) throws SyntaxException { String value = getSimple ( key ) ; return ( value == null ) ? defaultValue : value . toLowerCase ( ) . matches ( "(1|true|yes)" ) ; } | Return a property value typed as a Boolean |
12,116 | public Double getDouble ( String key , Double defaultValue ) throws SyntaxException { String value = getSimple ( key ) ; if ( value == null ) { return defaultValue ; } else { try { return Double . valueOf ( value ) ; } catch ( NumberFormatException e ) { throw new SyntaxException ( String . format ( "Invalid double value %s for '%s'" , value , key ) ) ; } } } | Return a property value typed as a Double |
12,117 | public Integer getInt ( String key , Integer defaultValue ) throws SyntaxException { String value = getSimple ( key ) ; return toInt ( key , value , defaultValue ) ; } | Return a property value typed as an Integer |
12,118 | public static ReplayPosition getReplayPosition ( Iterable < ? extends SSTableReader > sstables ) { if ( Iterables . isEmpty ( sstables ) ) return NONE ; Function < SSTableReader , ReplayPosition > f = new Function < SSTableReader , ReplayPosition > ( ) { public ReplayPosition apply ( SSTableReader sstable ) { return sstable . getReplayPosition ( ) ; } } ; Ordering < ReplayPosition > ordering = Ordering . from ( ReplayPosition . comparator ) ; return ordering . max ( Iterables . transform ( sstables , f ) ) ; } | Convenience method to compute the replay position for a group of SSTables . |
12,119 | public void setDiscarding ( ) { state = state . transition ( LifeCycle . DISCARDING ) ; onHeap . markAllReclaiming ( ) ; offHeap . markAllReclaiming ( ) ; } | Mark this allocator reclaiming ; this will permit any outstanding allocations to temporarily overshoot the maximum memory limit so that flushing can begin immediately |
12,120 | private < T extends Number > Gauge < Long > createKeyspaceGauge ( String name , final MetricValue extractor ) { allMetrics . add ( name ) ; return Metrics . newGauge ( factory . createMetricName ( name ) , new Gauge < Long > ( ) { public Long value ( ) { long sum = 0 ; for ( ColumnFamilyStore cf : keyspace . getColumnFamilyStores ( ) ) { sum += extractor . getValue ( cf . metric ) ; } return sum ; } } ) ; } | Creates a gauge that will sum the current value of a metric for all column families in this keyspace |
12,121 | 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 . |
12,122 | 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 ) ; big = big . or ( charbig . shiftLeft ( charpos ) ) ; } return big ; } | Copies the characters of the given string into a BigInteger . |
12,123 | private void setupDefaultUser ( ) { try { 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 ( hashpw ( DEFAULT_USER_PASSWORD ) ) ) , ConsistencyLevel . ONE ) ; logger . info ( "PasswordAuthenticator created default user '{}'" , DEFAULT_USER_NAME ) ; } } catch ( RequestExecutionException e ) { logger . warn ( "PasswordAuthenticator skipped default user setup: some nodes were not ready" ) ; } } | if there are no users yet - add default superuser . |
12,124 | 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 . |
12,125 | < V > void find ( Object [ ] node , Comparator < V > comparator , Object target , Op mode , boolean forwards ) { depth = - 1 ; if ( target instanceof BTree . Special ) { if ( target == POSITIVE_INFINITY ) moveEnd ( node , forwards ) ; else if ( target == NEGATIVE_INFINITY ) moveStart ( node , forwards ) ; else throw new AssertionError ( ) ; return ; } while ( true ) { int keyEnd = getKeyEnd ( node ) ; int i = BTree . find ( comparator , target , node , 0 , keyEnd ) ; if ( i >= 0 ) { push ( node , i ) ; switch ( mode ) { case HIGHER : successor ( ) ; break ; case LOWER : predecessor ( ) ; } return ; } i = - i - 1 ; if ( ! isLeaf ( node ) ) { push ( node , forwards ? i - 1 : i ) ; node = ( Object [ ] ) node [ keyEnd + i ] ; continue ; } switch ( mode ) { case FLOOR : case LOWER : i -- ; } if ( i < 0 ) { push ( node , 0 ) ; predecessor ( ) ; } else if ( i >= keyEnd ) { push ( node , keyEnd - 1 ) ; successor ( ) ; } else { push ( node , i ) ; } return ; } } | Find the provided key in the tree rooted at node and store the root to it in the path |
12,126 | void successor ( ) { Object [ ] node = currentNode ( ) ; int i = currentIndex ( ) ; if ( ! isLeaf ( node ) ) { node = ( Object [ ] ) node [ getBranchKeyEnd ( node ) + i + 1 ] ; while ( ! isLeaf ( node ) ) { push ( node , - 1 ) ; node = ( Object [ ] ) node [ getBranchKeyEnd ( node ) ] ; } push ( node , 0 ) ; return ; } i += 1 ; if ( i < getLeafKeyEnd ( node ) ) { setIndex ( i ) ; return ; } while ( ! isRoot ( ) ) { pop ( ) ; i = currentIndex ( ) + 1 ; node = currentNode ( ) ; if ( i < getKeyEnd ( node ) ) { setIndex ( i ) ; return ; } } setIndex ( getKeyEnd ( node ) ) ; } | move to the next key in the tree |
12,127 | 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 ( t , i , cassandraToObj ( result . get ( i ) . comparator , result . get ( i ) . value ) ) ; return t ; } | Deconstructs a composite type to a Tuple . |
12,128 | 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 ( ) ; if ( comparator instanceof AbstractCompositeType ) setTupleValue ( pair , 0 , composeComposite ( ( AbstractCompositeType ) comparator , colName ) ) ; else setTupleValue ( pair , 0 , cassandraToObj ( comparator , colName ) ) ; Map < ByteBuffer , AbstractType > validators = getValidatorMap ( cfDef ) ; if ( cfInfo . cql3Table && ! cfInfo . compactCqlTable ) { ByteBuffer [ ] names = ( ( AbstractCompositeType ) parseType ( cfDef . comparator_type ) ) . split ( colName ) ; colName = names [ names . length - 1 ] ; } if ( validators . get ( colName ) == null ) { Map < MarshallerType , AbstractType > marshallers = getDefaultMarshallers ( cfDef ) ; setTupleValue ( pair , 1 , cassandraToObj ( marshallers . get ( MarshallerType . DEFAULT_VALIDATOR ) , col . value ( ) ) ) ; } else setTupleValue ( pair , 1 , cassandraToObj ( validators . get ( colName ) , col . value ( ) ) ) ; return pair ; } | convert a column to a tuple |
12,129 | 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 = cfdefFromString ( prop . substring ( 2 ) ) ; cfInfo . compactCqlTable = prop . charAt ( 0 ) == '1' ? true : false ; cfInfo . cql3Table = prop . charAt ( 1 ) == '1' ? true : false ; return cfInfo ; } | get the columnfamily definition for the signature |
12,130 | 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 ; AbstractType key_validator ; comparator = parseType ( cfDef . getComparator_type ( ) ) ; subcomparator = parseType ( cfDef . getSubcomparator_type ( ) ) ; default_validator = parseType ( cfDef . getDefault_validation_class ( ) ) ; key_validator = parseType ( cfDef . getKey_validation_class ( ) ) ; marshallers . put ( MarshallerType . COMPARATOR , comparator ) ; marshallers . put ( MarshallerType . DEFAULT_VALIDATOR , default_validator ) ; marshallers . put ( MarshallerType . KEY_VALIDATOR , key_validator ) ; marshallers . put ( MarshallerType . SUBCOMPARATOR , subcomparator ) ; return marshallers ; } | construct a map to store the mashaller type to cassandra data type mapping |
12,131 | 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 ( ) . isEmpty ( ) ) { AbstractType validator = null ; try { validator = TypeParser . parse ( cd . getValidation_class ( ) ) ; if ( validator instanceof CounterColumnType ) validator = LongType . instance ; validators . put ( cd . name , validator ) ; } catch ( ConfigurationException e ) { throw new IOException ( e ) ; } catch ( SyntaxException e ) { throw new IOException ( e ) ; } } } return validators ; } | get the validators |
12,132 | protected AbstractType parseType ( String type ) throws IOException { try { if ( type != null && type . equals ( "org.apache.cassandra.db.marshal.CounterColumnType" ) ) return LongType . instance ; return TypeParser . parse ( type ) ; } catch ( ConfigurationException e ) { throw new IOException ( e ) ; } catch ( SyntaxException e ) { throw new IOException ( e ) ; } } | parse the string to a cassandra data type |
12,133 | 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 ] , URLDecoder . decode ( keyValue [ 1 ] , "UTF-8" ) ) ; } return map ; } | decompose the query to store the parameters in a map |
12,134 | protected byte getPigType ( AbstractType type ) { if ( type instanceof LongType || type instanceof DateType || type instanceof TimestampType ) return DataType . LONG ; else if ( type instanceof IntegerType || type instanceof Int32Type ) return DataType . INTEGER ; else if ( type instanceof AsciiType || type instanceof UTF8Type || type instanceof DecimalType || type instanceof InetAddressType ) return DataType . CHARARRAY ; else if ( type instanceof FloatType ) return DataType . FLOAT ; else if ( type instanceof DoubleType ) return DataType . DOUBLE ; else if ( type instanceof AbstractCompositeType || type instanceof CollectionType ) return DataType . TUPLE ; return DataType . BYTEARRAY ; } | get pig type for the cassandra data type |
12,135 | 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 LongType . instance . decompose ( ( Long ) o ) ; if ( o instanceof Float ) return FloatType . instance . decompose ( ( Float ) o ) ; if ( o instanceof Double ) return DoubleType . instance . decompose ( ( Double ) o ) ; if ( o instanceof UUID ) return ByteBuffer . wrap ( UUIDGen . decompose ( ( UUID ) o ) ) ; if ( o instanceof Tuple ) { List < Object > objects = ( ( Tuple ) o ) . getAll ( ) ; if ( objects . size ( ) > 0 && objects . get ( 0 ) instanceof String ) { String collectionType = ( String ) objects . get ( 0 ) ; if ( "set" . equalsIgnoreCase ( collectionType ) || "list" . equalsIgnoreCase ( collectionType ) ) return objToListOrSetBB ( objects . subList ( 1 , objects . size ( ) ) ) ; else if ( "map" . equalsIgnoreCase ( collectionType ) ) return objToMapBB ( objects . subList ( 1 , objects . size ( ) ) ) ; } return objToCompositeBB ( objects ) ; } return ByteBuffer . wrap ( ( ( DataByteArray ) o ) . get ( ) ) ; } | convert object to ByteBuffer |
12,136 | protected void initSchema ( String signature ) throws IOException { Properties properties = UDFContext . getUDFContext ( ) . getUDFProperties ( AbstractCassandraStorage . class ) ; if ( ! properties . containsKey ( signature ) ) { try { Cassandra . Client client = ConfigHelper . getClientFromInputAddressList ( conf ) ; client . set_keyspace ( keyspace ) ; if ( username != null && password != null ) { Map < String , String > credentials = new HashMap < String , String > ( 2 ) ; credentials . put ( IAuthenticator . USERNAME_KEY , username ) ; credentials . put ( IAuthenticator . PASSWORD_KEY , password ) ; try { client . login ( new AuthenticationRequest ( credentials ) ) ; } catch ( AuthenticationException e ) { logger . error ( "Authentication exception: invalid username and/or password" ) ; throw new IOException ( e ) ; } catch ( AuthorizationException e ) { throw new AssertionError ( e ) ; } } CfInfo cfInfo = getCfInfo ( client ) ; if ( cfInfo . cfDef != null ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( cfInfo . compactCqlTable ? 1 : 0 ) . append ( cfInfo . cql3Table ? 1 : 0 ) . append ( cfdefToString ( cfInfo . cfDef ) ) ; properties . setProperty ( signature , sb . toString ( ) ) ; } else throw new IOException ( String . format ( "Column family '%s' not found in keyspace '%s'" , column_family , keyspace ) ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } } } | Methods to get the column family schema from Cassandra |
12,137 | protected static String cfdefToString ( CfDef cfDef ) throws IOException { assert cfDef != null ; TSerializer serializer = new TSerializer ( new TBinaryProtocol . Factory ( ) ) ; try { return Hex . bytesToHex ( serializer . serialize ( cfDef ) ) ; } catch ( TException e ) { throw new IOException ( e ) ; } } | convert CfDef to string |
12,138 | 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 IOException ( e ) ; } return cfDef ; } | convert string back to CfDef |
12,139 | protected CfInfo getCfInfo ( Cassandra . Client client ) throws InvalidRequestException , UnavailableException , TimedOutException , SchemaDisagreementException , TException , NotFoundException , org . apache . cassandra . exceptions . InvalidRequestException , ConfigurationException , IOException { String query = "SELECT type," + " comparator," + " subcomparator," + " default_validator," + " key_validator," + " key_aliases " + "FROM system.schema_columnfamilies " + "WHERE keyspace_name = '%s' " + " AND columnfamily_name = '%s' " ; CqlResult result = client . execute_cql3_query ( ByteBufferUtil . bytes ( String . format ( query , keyspace , column_family ) ) , Compression . NONE , ConsistencyLevel . ONE ) ; if ( result == null || result . rows == null || result . rows . isEmpty ( ) ) return null ; Iterator < CqlRow > iteraRow = result . rows . iterator ( ) ; CfDef cfDef = new CfDef ( ) ; cfDef . keyspace = keyspace ; cfDef . name = column_family ; boolean cql3Table = false ; if ( iteraRow . hasNext ( ) ) { CqlRow cqlRow = iteraRow . next ( ) ; cfDef . column_type = ByteBufferUtil . string ( cqlRow . columns . get ( 0 ) . value ) ; cfDef . comparator_type = ByteBufferUtil . string ( cqlRow . columns . get ( 1 ) . value ) ; ByteBuffer subComparator = cqlRow . columns . get ( 2 ) . value ; if ( subComparator != null ) cfDef . subcomparator_type = ByteBufferUtil . string ( subComparator ) ; cfDef . default_validation_class = ByteBufferUtil . string ( cqlRow . columns . get ( 3 ) . value ) ; cfDef . key_validation_class = ByteBufferUtil . string ( cqlRow . columns . get ( 4 ) . value ) ; String keyAliases = ByteBufferUtil . string ( cqlRow . columns . get ( 5 ) . value ) ; if ( FBUtilities . fromJsonList ( keyAliases ) . size ( ) > 0 ) cql3Table = true ; } cfDef . column_metadata = getColumnMetadata ( client ) ; CfInfo cfInfo = new CfInfo ( ) ; cfInfo . cfDef = cfDef ; if ( cql3Table && ! ( parseType ( cfDef . comparator_type ) instanceof AbstractCompositeType ) ) cfInfo . compactCqlTable = true ; if ( cql3Table ) cfInfo . cql3Table = true ; ; return cfInfo ; } | return the CfInfo for the column family |
12,140 | protected List < ColumnDef > getColumnMeta ( Cassandra . Client client , boolean cassandraStorage , boolean includeCompactValueColumn ) throws InvalidRequestException , UnavailableException , TimedOutException , SchemaDisagreementException , TException , CharacterCodingException , org . apache . cassandra . exceptions . InvalidRequestException , ConfigurationException , NotFoundException { String query = "SELECT column_name, " + " validator, " + " index_type, " + " type " + "FROM system.schema_columns " + "WHERE keyspace_name = '%s' " + " AND columnfamily_name = '%s'" ; CqlResult result = client . execute_cql3_query ( ByteBufferUtil . bytes ( String . format ( query , keyspace , column_family ) ) , Compression . NONE , ConsistencyLevel . ONE ) ; List < CqlRow > rows = result . rows ; List < ColumnDef > columnDefs = new ArrayList < ColumnDef > ( ) ; if ( rows == null || rows . isEmpty ( ) ) { if ( cassandraStorage ) return columnDefs ; CFMetaData cfm = getCFMetaData ( keyspace , column_family , client ) ; for ( ColumnDefinition def : cfm . regularAndStaticColumns ( ) ) { ColumnDef cDef = new ColumnDef ( ) ; String columnName = def . name . toString ( ) ; String type = def . type . toString ( ) ; logger . debug ( "name: {}, type: {} " , columnName , type ) ; cDef . name = ByteBufferUtil . bytes ( columnName ) ; cDef . validation_class = type ; columnDefs . add ( cDef ) ; } if ( columnDefs . size ( ) == 0 && includeCompactValueColumn && cfm . compactValueColumn ( ) != null ) { ColumnDefinition def = cfm . compactValueColumn ( ) ; if ( "value" . equals ( def . name . toString ( ) ) ) { ColumnDef cDef = new ColumnDef ( ) ; cDef . name = def . name . bytes ; cDef . validation_class = def . type . toString ( ) ; columnDefs . add ( cDef ) ; } } return columnDefs ; } Iterator < CqlRow > iterator = rows . iterator ( ) ; while ( iterator . hasNext ( ) ) { CqlRow row = iterator . next ( ) ; ColumnDef cDef = new ColumnDef ( ) ; String type = ByteBufferUtil . string ( row . getColumns ( ) . get ( 3 ) . value ) ; if ( ! type . equals ( "regular" ) ) continue ; cDef . setName ( ByteBufferUtil . clone ( row . getColumns ( ) . get ( 0 ) . value ) ) ; cDef . validation_class = ByteBufferUtil . string ( row . getColumns ( ) . get ( 1 ) . value ) ; ByteBuffer indexType = row . getColumns ( ) . get ( 2 ) . value ; if ( indexType != null ) cDef . index_type = getIndexType ( ByteBufferUtil . string ( indexType ) ) ; columnDefs . add ( cDef ) ; } return columnDefs ; } | get column meta data |
12,141 | 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 |
12,142 | 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 String ( indexes . get ( i ) . getName ( ) ) ; } return partitionKeys ; } | return partition keys |
12,143 | 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 |
12,144 | 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 : ksDef . cf_defs ) { if ( cfDef . name . equalsIgnoreCase ( cf ) ) return CFMetaData . fromThrift ( cfDef ) ; } return null ; } | get CFMetaData of a column family |
12,145 | 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 . |
12,146 | 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 . |
12,147 | 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 . |
12,148 | private long beforeAppend ( DecoratedKey decoratedKey ) { assert decoratedKey != null : "Keys must not be null" ; if ( lastWrittenKey != null && lastWrittenKey . compareTo ( decoratedKey ) >= 0 ) throw new RuntimeException ( "Last written key " + lastWrittenKey + " >= current key " + decoratedKey + " writing into " + getFilename ( ) ) ; return ( lastWrittenKey == null ) ? 0 : dataFile . getFilePointer ( ) ; } | Perform sanity checks on |
12,149 | 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 ( ) ) SSTable . delete ( descriptor , components ) ; } catch ( FSWriteError e ) { logger . error ( String . format ( "Failed deleting temp components for %s" , descriptor ) , e ) ; throw e ; } } | After failure attempt to close the index writer and data file before deleting all temp components for the sstable |
12,150 | 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 |
12,151 | 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 = false ; try { if ( usePessimisticLocking ( ) ) { Locks . monitorEnterUnsafe ( this ) ; monitorOwned = true ; } while ( true ) { Holder current = ref ; updater . ref = current ; updater . reset ( ) ; DeletionInfo deletionInfo ; if ( cm . deletionInfo ( ) . mayModify ( current . deletionInfo ) ) { if ( inputDeletionInfoCopy == null ) inputDeletionInfoCopy = cm . deletionInfo ( ) . copy ( HeapAllocator . instance ) ; deletionInfo = current . deletionInfo . copy ( ) . add ( inputDeletionInfoCopy ) ; updater . allocated ( deletionInfo . unsharedHeapSize ( ) - current . deletionInfo . unsharedHeapSize ( ) ) ; } else { deletionInfo = current . deletionInfo ; } Object [ ] tree = BTree . update ( current . tree , metadata . comparator . columnComparator ( Memtable . MEMORY_POOL instanceof NativePool ) , cm , cm . getColumnCount ( ) , true , updater ) ; if ( tree != null && refUpdater . compareAndSet ( this , current , new Holder ( tree , deletionInfo ) ) ) { indexer . updateRowLevelIndexes ( ) ; updater . finish ( ) ; return Pair . create ( updater . dataSize , updater . colUpdateTimeDelta ) ; } else if ( ! monitorOwned ) { boolean shouldLock = usePessimisticLocking ( ) ; if ( ! shouldLock ) { shouldLock = updateWastedAllocationTracker ( updater . heapSize ) ; } if ( shouldLock ) { Locks . monitorEnterUnsafe ( this ) ; monitorOwned = true ; } } } } finally { if ( monitorOwned ) Locks . monitorExitUnsafe ( this ) ; } } | This is only called by Memtable . resolve so only AtomicBTreeColumns needs to implement it . |
12,152 | private boolean updateWastedAllocationTracker ( long wastedBytes ) { if ( wastedBytes < EXCESS_WASTE_BYTES ) { int wastedAllocation = ( ( int ) ( wastedBytes + ALLOCATION_GRANULARITY_BYTES - 1 ) ) / ALLOCATION_GRANULARITY_BYTES ; int oldTrackerValue ; while ( TRACKER_PESSIMISTIC_LOCKING != ( oldTrackerValue = wasteTracker ) ) { int time = ( int ) ( System . nanoTime ( ) >>> CLOCK_SHIFT ) ; int delta = oldTrackerValue - time ; if ( oldTrackerValue == TRACKER_NEVER_WASTED || delta >= 0 || delta < - EXCESS_WASTE_OFFSET ) delta = - EXCESS_WASTE_OFFSET ; delta += wastedAllocation ; if ( delta >= 0 ) break ; if ( wasteTrackerUpdater . compareAndSet ( this , oldTrackerValue , avoidReservedValues ( time + delta ) ) ) return false ; } } wasteTrackerUpdater . set ( this , TRACKER_PESSIMISTIC_LOCKING ) ; return true ; } | Update the wasted allocation tracker state based on newly wasted allocation information |
12,153 | 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 . position ( ) + length ) ; } return readValue ( input , Server . VERSION_3 ) ; } catch ( BufferUnderflowException e ) { throw new MarshalException ( "Not enough bytes to read a list" ) ; } } | Returns the element at the given index in a list . |
12,154 | 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 |
12,155 | 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 . |
12,156 | 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 . |
12,157 | 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 . resultify ( query , serializedTriggers ) ) { String name = row . getString ( TRIGGER_NAME ) ; String classOption = row . getMap ( TRIGGER_OPTIONS , UTF8Type . instance , UTF8Type . instance ) . get ( CLASS ) ; triggers . add ( new TriggerDefinition ( name , classOption ) ) ; } return triggers ; } | Deserialize triggers from storage - level representation . |
12,158 | 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 , timestamp ) ; adder . addMapEntry ( TRIGGER_OPTIONS , CLASS , classOption ) ; } | Add specified trigger to the schema using given mutation . |
12,159 | 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 . addAtom ( new RangeTombstone ( prefix , prefix . end ( ) , timestamp , ldt ) ) ; } | Drop specified trigger from the schema using given mutation . |
12,160 | 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 |
12,161 | NodeBuilder update ( Object key ) { assert copyFrom != null ; int copyFromKeyEnd = getKeyEnd ( copyFrom ) ; int i = copyFromKeyPosition ; boolean found ; boolean owns = true ; if ( i == copyFromKeyEnd ) { found = false ; } else { int c = - comparator . compare ( key , copyFrom [ i ] ) ; if ( c >= 0 ) { found = c == 0 ; } else { i = find ( comparator , key , copyFrom , i + 1 , copyFromKeyEnd ) ; found = i >= 0 ; if ( ! found ) i = - i - 1 ; } } if ( found ) { Object prev = copyFrom [ i ] ; Object next = updateFunction . apply ( prev , key ) ; if ( prev == next ) return null ; key = next ; } else if ( i == copyFromKeyEnd && compare ( comparator , key , upperBound ) >= 0 ) owns = false ; if ( isLeaf ( copyFrom ) ) { if ( owns ) { copyKeys ( i ) ; if ( found ) { replaceNextKey ( key ) ; } else { key = updateFunction . apply ( key ) ; addNewKey ( key ) ; } return null ; } else { if ( buildKeyPosition > 0 ) copyKeys ( i ) ; } } else { if ( found ) { copyKeys ( i ) ; replaceNextKey ( key ) ; copyChildren ( i + 1 ) ; return null ; } else if ( owns ) { copyKeys ( i ) ; copyChildren ( i ) ; Object newUpperBound = i < copyFromKeyEnd ? copyFrom [ i ] : upperBound ; Object [ ] descendInto = ( Object [ ] ) copyFrom [ copyFromKeyEnd + i ] ; ensureChild ( ) . reset ( descendInto , newUpperBound , updateFunction , comparator ) ; return child ; } else if ( buildKeyPosition > 0 || buildChildPosition > 0 ) { copyKeys ( copyFromKeyEnd ) ; copyChildren ( copyFromKeyEnd + 1 ) ; } } return ascend ( ) ; } | Inserts or replaces the provided key copying all not - yet - visited keys prior to it into our buffer . |
12,162 | 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 |
12,163 | 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 |
12,164 | private NodeBuilder ascend ( ) { ensureParent ( ) ; boolean isLeaf = isLeaf ( copyFrom ) ; if ( buildKeyPosition > FAN_FACTOR ) { int mid = buildKeyPosition / 2 ; parent . addExtraChild ( buildFromRange ( 0 , mid , isLeaf , true ) , buildKeys [ mid ] ) ; parent . finishChild ( buildFromRange ( mid + 1 , buildKeyPosition - ( mid + 1 ) , isLeaf , false ) ) ; } else { parent . finishChild ( buildFromRange ( 0 , buildKeyPosition , isLeaf , false ) ) ; } return parent ; } | finish up this level and pass any constructed children up to our parent ensuring a parent exists |
12,165 | 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 |
12,166 | 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 |
12,167 | private void ensureRoom ( int nextBuildKeyPosition ) { if ( nextBuildKeyPosition < MAX_KEYS ) return ; Object [ ] flushUp = buildFromRange ( 0 , FAN_FACTOR , isLeaf ( copyFrom ) , true ) ; ensureParent ( ) . addExtraChild ( flushUp , buildKeys [ FAN_FACTOR ] ) ; int size = FAN_FACTOR + 1 ; assert size <= buildKeyPosition : buildKeyPosition + "," + nextBuildKeyPosition ; System . arraycopy ( buildKeys , size , buildKeys , 0 , buildKeyPosition - size ) ; buildKeyPosition -= size ; maxBuildKeyPosition = buildKeys . length ; if ( buildChildPosition > 0 ) { System . arraycopy ( buildChildren , size , buildChildren , 0 , buildChildPosition - size ) ; buildChildPosition -= size ; } } | checks if we can add the requested keys + children to the builder and if not we spill - over into our parent |
12,168 | private Object [ ] buildFromRange ( int offset , int keyLength , boolean isLeaf , boolean isExtra ) { if ( keyLength == 0 ) return copyFrom ; Object [ ] a ; if ( isLeaf ) { a = new Object [ keyLength + ( keyLength & 1 ) ] ; System . arraycopy ( buildKeys , offset , a , 0 , keyLength ) ; } else { a = new Object [ 1 + ( keyLength * 2 ) ] ; System . arraycopy ( buildKeys , offset , a , 0 , keyLength ) ; System . arraycopy ( buildChildren , offset , a , keyLength , keyLength + 1 ) ; } if ( isExtra ) updateFunction . allocated ( ObjectSizes . sizeOfArray ( a ) ) ; else if ( a . length != copyFrom . length ) updateFunction . allocated ( ObjectSizes . sizeOfArray ( a ) - ( copyFrom . length == 0 ? 0 : ObjectSizes . sizeOfArray ( copyFrom ) ) ) ; return a ; } | builds and returns a node from the buffered objects in the given range |
12,169 | 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 |
12,170 | 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 == lastSection . right ) { lastSection = Pair . create ( lastSection . left , chunk . offset + chunk . length + 4 ) ; } else { transferSections . add ( lastSection ) ; lastSection = Pair . create ( chunk . offset , chunk . offset + chunk . length + 4 ) ; } } else { lastSection = Pair . create ( chunk . offset , chunk . offset + chunk . length + 4 ) ; } } if ( lastSection != null ) transferSections . add ( lastSection ) ; return transferSections ; } | chunks are assumed to be sorted by offset |
12,171 | public CellName copy ( CFMetaData cfm , AbstractAllocator allocator ) { return new SimpleDenseCellName ( allocator . clone ( element ) ) ; } | we might want to try to do better . |
12,172 | 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 . |
12,173 | 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 > ( ) { public boolean apply ( SSTableReader sstable ) { return sstable . getMaxTimestamp ( ) >= cutoff ; } } ) ; } | Removes all sstables with max timestamp older than maxSSTableAge . |
12,174 | static < T > List < List < T > > getBuckets ( Collection < Pair < T , Long > > files , long timeUnit , int base , long now ) { final List < Pair < T , Long > > sortedFiles = Lists . newArrayList ( files ) ; Collections . sort ( sortedFiles , Collections . reverseOrder ( new Comparator < Pair < T , Long > > ( ) { public int compare ( Pair < T , Long > p1 , Pair < T , Long > p2 ) { return p1 . right . compareTo ( p2 . right ) ; } } ) ) ; List < List < T > > buckets = Lists . newArrayList ( ) ; Target target = getInitialTarget ( now , timeUnit ) ; PeekingIterator < Pair < T , Long > > it = Iterators . peekingIterator ( sortedFiles . iterator ( ) ) ; outerLoop : while ( it . hasNext ( ) ) { while ( ! target . onTarget ( it . peek ( ) . right ) ) { if ( target . compareToTimestamp ( it . peek ( ) . right ) < 0 ) { it . next ( ) ; if ( ! it . hasNext ( ) ) break outerLoop ; } else target = target . nextTarget ( base ) ; } List < T > bucket = Lists . newArrayList ( ) ; while ( target . onTarget ( it . peek ( ) . right ) ) { bucket . add ( it . next ( ) . left ) ; if ( ! it . hasNext ( ) ) break ; } buckets . add ( bucket ) ; } return buckets ; } | 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 . |
12,175 | 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 ( InvalidRequestException e ) { throw new IOException ( "Error adding row with key: " + key , e ) ; } } | The column values must correspond to the order in which they appear in the insert stored procedure . |
12,176 | 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 |
12,177 | public static boolean delete ( Descriptor desc , Set < Component > components ) { if ( components . contains ( Component . DATA ) ) FileUtils . deleteWithConfirm ( desc . filenameFor ( Component . DATA ) ) ; for ( Component component : components ) { if ( component . equals ( Component . DATA ) || component . equals ( Component . SUMMARY ) ) continue ; FileUtils . deleteWithConfirm ( desc . filenameFor ( component ) ) ; } FileUtils . delete ( desc . filenameFor ( Component . SUMMARY ) ) ; logger . debug ( "Deleted {}" , desc ) ; return true ; } | 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 the file should be removed . |
12,178 | 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 |
12,179 | 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 . newHashSetWithExpectedSize ( componentNames . size ( ) ) ; for ( String componentName : componentNames ) { Component component = new Component ( Component . Type . fromRepresentation ( componentName ) , componentName ) ; if ( ! new File ( descriptor . filenameFor ( component ) ) . exists ( ) ) logger . error ( "Missing component: {}" , descriptor . filenameFor ( component ) ) ; else components . add ( component ) ; } return components ; } | Reads the list of components from the TOC component . |
12,180 | 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 ( component . name ) ; } catch ( IOException e ) { throw new FSWriteError ( e , tocFile ) ; } finally { FileUtils . closeQuietly ( w ) ; } } | Appends new component names to the TOC component . |
12,181 | 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 . |
12,182 | 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 ) ; CompactionMetadata compaction = ( CompactionMetadata ) components . get ( MetadataType . COMPACTION ) ; assert validation != null && stats != null && compaction != null && validation . partitioner != null ; EstimatedHistogram . serializer . serialize ( stats . estimatedRowSize , out ) ; EstimatedHistogram . serializer . serialize ( stats . estimatedColumnCount , out ) ; ReplayPosition . serializer . serialize ( stats . replayPosition , out ) ; out . writeLong ( stats . minTimestamp ) ; out . writeLong ( stats . maxTimestamp ) ; out . writeInt ( stats . maxLocalDeletionTime ) ; out . writeDouble ( validation . bloomFilterFPChance ) ; out . writeDouble ( stats . compressionRatio ) ; out . writeUTF ( validation . partitioner ) ; out . writeInt ( compaction . ancestors . size ( ) ) ; for ( Integer g : compaction . ancestors ) out . writeInt ( g ) ; StreamingHistogram . serializer . serialize ( stats . estimatedTombstoneDropTime , out ) ; out . writeInt ( stats . sstableLevel ) ; out . writeInt ( stats . minColumnNames . size ( ) ) ; for ( ByteBuffer columnName : stats . minColumnNames ) ByteBufferUtil . writeWithShortLength ( columnName , out ) ; out . writeInt ( stats . maxColumnNames . size ( ) ) ; for ( ByteBuffer columnName : stats . maxColumnNames ) ByteBufferUtil . writeWithShortLength ( columnName , out ) ; } | Legacy serialization is only used for SSTable level reset . |
12,183 | 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 ( ! statsFile . exists ( ) && types . contains ( MetadataType . STATS ) ) { components . put ( MetadataType . STATS , MetadataCollector . defaultStatsMetadata ( ) ) ; } else { try ( DataInputStream in = new DataInputStream ( new BufferedInputStream ( new FileInputStream ( statsFile ) ) ) ) { EstimatedHistogram rowSizes = EstimatedHistogram . serializer . deserialize ( in ) ; EstimatedHistogram columnCounts = EstimatedHistogram . serializer . deserialize ( in ) ; ReplayPosition replayPosition = ReplayPosition . serializer . deserialize ( in ) ; long minTimestamp = in . readLong ( ) ; long maxTimestamp = in . readLong ( ) ; int maxLocalDeletionTime = in . readInt ( ) ; double bloomFilterFPChance = in . readDouble ( ) ; double compressionRatio = in . readDouble ( ) ; String partitioner = in . readUTF ( ) ; int nbAncestors = in . readInt ( ) ; Set < Integer > ancestors = new HashSet < > ( nbAncestors ) ; for ( int i = 0 ; i < nbAncestors ; i ++ ) ancestors . add ( in . readInt ( ) ) ; StreamingHistogram tombstoneHistogram = StreamingHistogram . serializer . deserialize ( in ) ; int sstableLevel = 0 ; if ( in . available ( ) > 0 ) sstableLevel = in . readInt ( ) ; int colCount = in . readInt ( ) ; List < ByteBuffer > minColumnNames = new ArrayList < > ( colCount ) ; for ( int i = 0 ; i < colCount ; i ++ ) minColumnNames . add ( ByteBufferUtil . readWithShortLength ( in ) ) ; colCount = in . readInt ( ) ; List < ByteBuffer > maxColumnNames = new ArrayList < > ( colCount ) ; for ( int i = 0 ; i < colCount ; i ++ ) maxColumnNames . add ( ByteBufferUtil . readWithShortLength ( in ) ) ; if ( types . contains ( MetadataType . VALIDATION ) ) components . put ( MetadataType . VALIDATION , new ValidationMetadata ( partitioner , bloomFilterFPChance ) ) ; if ( types . contains ( MetadataType . STATS ) ) components . put ( MetadataType . STATS , new StatsMetadata ( rowSizes , columnCounts , replayPosition , minTimestamp , maxTimestamp , maxLocalDeletionTime , compressionRatio , tombstoneHistogram , sstableLevel , minColumnNames , maxColumnNames , true , ActiveRepairService . UNREPAIRED_SSTABLE ) ) ; if ( types . contains ( MetadataType . COMPACTION ) ) components . put ( MetadataType . COMPACTION , new CompactionMetadata ( ancestors , null ) ) ; } } return components ; } | Legacy serializer deserialize all components no matter what types are specified . |
12,184 | 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 , true ) ; logger . debug ( "[Stream #{}] Sending stream init for outgoing stream" , session . planId ( ) ) ; Socket outgoingSocket = session . createConnection ( ) ; outgoing . start ( outgoingSocket , StreamMessage . CURRENT_VERSION ) ; outgoing . sendInitMessage ( outgoingSocket , false ) ; } | Set up incoming message handler and initiate streaming . |
12,185 | 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 . |
12,186 | 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 |
12,187 | 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 ; } int sizeAtFullSampling = ( int ) Math . ceil ( keysWritten / ( double ) minIndexInterval ) ; assert count > 0 ; return new IndexSummary ( partitioner , offsets . currentBuffer ( ) . sharedCopy ( ) , count , entries . currentBuffer ( ) . sharedCopy ( ) , entriesLength , sizeAtFullSampling , minIndexInterval , samplingLevel ) ; } | multiple invocations of this build method |
12,188 | public static IndexSummary downsample ( IndexSummary existing , int newSamplingLevel , int minIndexInterval , IPartitioner partitioner ) { int currentSamplingLevel = existing . getSamplingLevel ( ) ; assert currentSamplingLevel > newSamplingLevel ; assert minIndexInterval == existing . getMinIndexInterval ( ) ; int [ ] startPoints = Downsampling . getStartPoints ( currentSamplingLevel , newSamplingLevel ) ; int newKeyCount = existing . size ( ) ; long newEntriesLength = existing . getEntriesLength ( ) ; for ( int start : startPoints ) { for ( int j = start ; j < existing . size ( ) ; j += currentSamplingLevel ) { newKeyCount -- ; long length = existing . getEndInSummary ( j ) - existing . getPositionInSummary ( j ) ; newEntriesLength -= length ; } } Memory oldEntries = existing . getEntries ( ) ; Memory newOffsets = Memory . allocate ( newKeyCount * 4 ) ; Memory newEntries = Memory . allocate ( newEntriesLength ) ; int i = 0 ; int newEntriesOffset = 0 ; outer : for ( int oldSummaryIndex = 0 ; oldSummaryIndex < existing . size ( ) ; oldSummaryIndex ++ ) { for ( int start : startPoints ) { if ( ( oldSummaryIndex - start ) % currentSamplingLevel == 0 ) continue outer ; } newOffsets . setInt ( i * 4 , newEntriesOffset ) ; i ++ ; long start = existing . getPositionInSummary ( oldSummaryIndex ) ; long length = existing . getEndInSummary ( oldSummaryIndex ) - start ; newEntries . put ( newEntriesOffset , oldEntries , start , length ) ; newEntriesOffset += length ; } assert newEntriesOffset == newEntriesLength ; return new IndexSummary ( partitioner , newOffsets , newKeyCount , newEntries , newEntriesLength , existing . getMaxNumberOfEntries ( ) , minIndexInterval , newSamplingLevel ) ; } | Downsamples an existing index summary to a new sampling level . |
12,189 | public void update ( double p , long m ) { Long mi = bin . get ( p ) ; if ( mi != null ) { bin . put ( p , mi + m ) ; } else { bin . put ( p , m ) ; while ( bin . size ( ) > maxBinSize ) { Iterator < Double > keys = bin . keySet ( ) . iterator ( ) ; double p1 = keys . next ( ) ; double p2 = keys . next ( ) ; double smallestDiff = p2 - p1 ; double q1 = p1 , q2 = p2 ; while ( keys . hasNext ( ) ) { p1 = p2 ; p2 = keys . next ( ) ; double diff = p2 - p1 ; if ( diff < smallestDiff ) { smallestDiff = diff ; q1 = p1 ; q2 = p2 ; } } long k1 = bin . remove ( q1 ) ; long k2 = bin . remove ( q2 ) ; bin . put ( ( q1 * k1 + q2 * k2 ) / ( k1 + k2 ) , k1 + k2 ) ; } } } | Adds new point p with value m to this histogram . |
12,190 | public RateLimiter getRateLimiter ( ) { double currentThroughput = DatabaseDescriptor . getCompactionThroughputMbPerSec ( ) * 1024.0 * 1024.0 ; if ( currentThroughput == 0 || StorageService . instance . isBootstrapMode ( ) ) currentThroughput = Double . MAX_VALUE ; if ( compactionRateLimiter . getRate ( ) != currentThroughput ) compactionRateLimiter . setRate ( currentThroughput ) ; return compactionRateLimiter ; } | 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 . |
12,191 | 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 |
12,192 | 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 ) { validator . fail ( ) ; throw e ; } return this ; } } ; return validationExecutor . submit ( callable ) ; } | Does not mutate data so is not scheduled . |
12,193 | static boolean needsCleanup ( SSTableReader sstable , Collection < Range < Token > > ownedRanges ) { assert ! ownedRanges . isEmpty ( ) ; List < Range < Token > > sortedRanges = Range . normalize ( ownedRanges ) ; Range < Token > firstRange = sortedRanges . get ( 0 ) ; if ( sstable . first . getToken ( ) . compareTo ( firstRange . left ) <= 0 ) return true ; for ( int i = 0 ; i < sortedRanges . size ( ) ; i ++ ) { Range < Token > range = sortedRanges . get ( i ) ; if ( range . right . isMinimum ( ) ) { return false ; } DecoratedKey firstBeyondRange = sstable . firstKeyBeyond ( range . right . maxKeyBound ( ) ) ; if ( firstBeyondRange == null ) { return false ; } if ( i == ( sortedRanges . size ( ) - 1 ) ) { return true ; } Range < Token > nextRange = sortedRanges . get ( i + 1 ) ; if ( ! nextRange . contains ( firstBeyondRange . getToken ( ) ) ) { return true ; } } return false ; } | Determines if a cleanup would actually remove any data in this SSTable based on a set of owned ranges . |
12,194 | 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 ( "Compaction executor has shut down, not submitting index build" ) ; return null ; } return executor . submit ( runnable ) ; } | Is not scheduled because it is performing disjoint work from sstable compaction . |
12,195 | public void interruptCompactionFor ( Iterable < CFMetaData > columnFamilies , boolean interruptValidation ) { assert columnFamilies != null ; for ( Holder compactionHolder : CompactionMetrics . getCompactions ( ) ) { CompactionInfo info = compactionHolder . getCompactionInfo ( ) ; if ( ( info . getTaskType ( ) == OperationType . VALIDATION ) && ! interruptValidation ) continue ; if ( Iterables . contains ( columnFamilies , info . getCFMetaData ( ) ) ) compactionHolder . stop ( ) ; } } | Try to stop all of the compactions for given ColumnFamilies . |
12,196 | 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 . getColumnCount ( ) ) cells = new Cell [ Math . max ( MINIMAL_CAPACITY , other . getColumnCount ( ) ) ] ; Iterator < Cell > iterator = reversed ? other . reverseIterator ( ) : other . iterator ( ) ; while ( iterator . hasNext ( ) ) cells [ size ++ ] = iterator . next ( ) ; sortedSize = size ; isSorted = true ; } } | Fast path when this ABSC is empty . |
12,197 | 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 . |
12,198 | 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 . |
12,199 | private Region getRegion ( ) { while ( true ) { Region region = currentRegion . get ( ) ; if ( region != null ) return region ; region = RACE_ALLOCATED . poll ( ) ; if ( region == null ) region = new Region ( allocateOnHeapOnly ? ByteBuffer . allocate ( REGION_SIZE ) : ByteBuffer . allocateDirect ( REGION_SIZE ) ) ; if ( currentRegion . compareAndSet ( null , region ) ) { if ( ! allocateOnHeapOnly ) offHeapRegions . add ( region ) ; regionCount . incrementAndGet ( ) ; logger . trace ( "{} regions now allocated in {}" , regionCount , this ) ; return region ; } RACE_ALLOCATED . add ( region ) ; } } | Get the current region or if there is no current region allocate a new one |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.