idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
12,200 | private void executeAddColumnFamily ( Tree statement ) { if ( ! CliMain . isConnected ( ) || ! hasKeySpace ( ) ) return ; // first value is the column family name, after that it is all key=value CfDef cfDef = new CfDef ( keySpace , CliUtils . unescapeSQLString ( statement . getChild ( 0 ) . getText ( ) ) ) ; try { String mySchemaVersion = thriftClient . system_add_column_family ( updateCfDefAttributes ( statement , cfDef ) ) ; sessionState . out . println ( mySchemaVersion ) ; keyspacesMap . put ( keySpace , thriftClient . describe_keyspace ( keySpace ) ) ; } catch ( InvalidRequestException e ) { throw new RuntimeException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Add a column family | 190 | 4 |
12,201 | private void executeUpdateKeySpace ( Tree statement ) { if ( ! CliMain . isConnected ( ) ) return ; try { String keyspaceName = CliCompiler . getKeySpace ( statement , thriftClient . describe_keyspaces ( ) ) ; KsDef currentKsDef = getKSMetaData ( keyspaceName ) ; KsDef updatedKsDef = updateKsDefAttributes ( statement , currentKsDef ) ; String mySchemaVersion = thriftClient . system_update_keyspace ( updatedKsDef ) ; sessionState . out . println ( mySchemaVersion ) ; keyspacesMap . remove ( keyspaceName ) ; getKSMetaData ( keyspaceName ) ; } catch ( InvalidRequestException e ) { throw new RuntimeException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Update existing keyspace identified by name | 187 | 7 |
12,202 | private void executeUpdateColumnFamily ( Tree statement ) { if ( ! CliMain . isConnected ( ) || ! hasKeySpace ( ) ) return ; String cfName = CliCompiler . getColumnFamily ( statement , currentCfDefs ( ) ) ; try { // request correct cfDef from the server (we let that call include CQL3 cf even though // they can't be modified by thrift because the error message that will be thrown by // system_update_column_family will be more useful) CfDef cfDef = getCfDef ( thriftClient . describe_keyspace ( this . keySpace ) , cfName , true ) ; if ( cfDef == null ) throw new RuntimeException ( "Column Family " + cfName + " was not found in the current keyspace." ) ; String mySchemaVersion = thriftClient . system_update_column_family ( updateCfDefAttributes ( statement , cfDef ) ) ; sessionState . out . println ( mySchemaVersion ) ; keyspacesMap . put ( keySpace , thriftClient . describe_keyspace ( keySpace ) ) ; } catch ( InvalidRequestException e ) { throw new RuntimeException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Update existing column family identified by name | 274 | 7 |
12,203 | private KsDef updateKsDefAttributes ( Tree statement , KsDef ksDefToUpdate ) { KsDef ksDef = new KsDef ( ksDefToUpdate ) ; // removing all column definitions - thrift system_update_keyspace method requires that ksDef . setCf_defs ( new LinkedList < CfDef > ( ) ) ; for ( int i = 1 ; i < statement . getChildCount ( ) ; i += 2 ) { String currentStatement = statement . getChild ( i ) . getText ( ) . toUpperCase ( ) ; AddKeyspaceArgument mArgument = AddKeyspaceArgument . valueOf ( currentStatement ) ; String mValue = statement . getChild ( i + 1 ) . getText ( ) ; switch ( mArgument ) { case PLACEMENT_STRATEGY : ksDef . setStrategy_class ( CliUtils . unescapeSQLString ( mValue ) ) ; break ; case STRATEGY_OPTIONS : ksDef . setStrategy_options ( getStrategyOptionsFromTree ( statement . getChild ( i + 1 ) ) ) ; break ; case DURABLE_WRITES : ksDef . setDurable_writes ( Boolean . parseBoolean ( mValue ) ) ; break ; default : //must match one of the above or we'd throw an exception at the valueOf statement above. assert ( false ) ; } } // using default snitch options if strategy is NetworkTopologyStrategy and no options were set. if ( ksDef . getStrategy_class ( ) . contains ( ".NetworkTopologyStrategy" ) ) { Map < String , String > currentStrategyOptions = ksDef . getStrategy_options ( ) ; // adding default data center from SimpleSnitch if ( currentStrategyOptions == null || currentStrategyOptions . isEmpty ( ) ) { SimpleSnitch snitch = new SimpleSnitch ( ) ; Map < String , String > options = new HashMap < String , String > ( ) ; try { options . put ( snitch . getDatacenter ( InetAddress . getLocalHost ( ) ) , "1" ) ; } catch ( UnknownHostException e ) { throw new RuntimeException ( e ) ; } ksDef . setStrategy_options ( options ) ; } } return ksDef ; } | Used to update keyspace definition attributes | 513 | 7 |
12,204 | private void executeDelKeySpace ( Tree statement ) throws TException , InvalidRequestException , NotFoundException , SchemaDisagreementException { if ( ! CliMain . isConnected ( ) ) return ; String keyspaceName = CliCompiler . getKeySpace ( statement , thriftClient . describe_keyspaces ( ) ) ; String version = thriftClient . system_drop_keyspace ( keyspaceName ) ; sessionState . out . println ( version ) ; if ( keyspaceName . equals ( keySpace ) ) //we just deleted the keyspace we were authenticated too keySpace = null ; } | Delete a keyspace | 130 | 4 |
12,205 | private void executeDelColumnFamily ( Tree statement ) throws TException , InvalidRequestException , NotFoundException , SchemaDisagreementException { if ( ! CliMain . isConnected ( ) || ! hasKeySpace ( ) ) return ; String cfName = CliCompiler . getColumnFamily ( statement , currentCfDefs ( ) ) ; String mySchemaVersion = thriftClient . system_drop_column_family ( cfName ) ; sessionState . out . println ( mySchemaVersion ) ; } | Delete a column family | 111 | 4 |
12,206 | private void showColumnMeta ( PrintStream output , CfDef cfDef , ColumnDef colDef ) { output . append ( NEWLINE + TAB + TAB + "{" ) ; final AbstractType < ? > comparator = getFormatType ( cfDef . column_type . equals ( "Super" ) ? cfDef . subcomparator_type : cfDef . comparator_type ) ; output . append ( "column_name : '" + CliUtils . escapeSQLString ( comparator . getString ( colDef . name ) ) + "'," + NEWLINE ) ; String validationClass = normaliseType ( colDef . validation_class , "org.apache.cassandra.db.marshal" ) ; output . append ( TAB + TAB + "validation_class : " + CliUtils . escapeSQLString ( validationClass ) ) ; if ( colDef . isSetIndex_name ( ) ) { output . append ( "," ) . append ( NEWLINE ) . append ( TAB + TAB + "index_name : '" + CliUtils . escapeSQLString ( colDef . index_name ) + "'," + NEWLINE ) . append ( TAB + TAB + "index_type : " + CliUtils . escapeSQLString ( Integer . toString ( colDef . index_type . getValue ( ) ) ) ) ; if ( colDef . index_options != null && ! colDef . index_options . isEmpty ( ) ) { output . append ( "," ) . append ( NEWLINE ) ; output . append ( TAB + TAB + "index_options : {" + NEWLINE ) ; int numOpts = colDef . index_options . size ( ) ; for ( Map . Entry < String , String > entry : colDef . index_options . entrySet ( ) ) { String option = CliUtils . escapeSQLString ( entry . getKey ( ) ) ; String optionValue = CliUtils . escapeSQLString ( entry . getValue ( ) ) ; output . append ( TAB + TAB + TAB ) . append ( "'" + option + "' : '" ) . append ( optionValue ) . append ( "'" ) ; if ( -- numOpts > 0 ) output . append ( "," ) . append ( NEWLINE ) ; } output . append ( "}" ) ; } } output . append ( "}" ) ; } | Writes the supplied ColumnDef to the StringBuilder as a cli script . | 525 | 16 |
12,207 | private boolean hasKeySpace ( boolean printError ) { boolean hasKeyspace = keySpace != null ; if ( ! hasKeyspace && printError ) sessionState . err . println ( "Not authorized to a working keyspace." ) ; return hasKeyspace ; } | Returns true if this . keySpace is set false otherwise | 55 | 11 |
12,208 | private IndexType getIndexTypeFromString ( String indexTypeAsString ) { IndexType indexType ; try { indexType = IndexType . findByValue ( new Integer ( indexTypeAsString ) ) ; } catch ( NumberFormatException e ) { try { // if this is not an integer lets try to get IndexType by name indexType = IndexType . valueOf ( indexTypeAsString ) ; } catch ( IllegalArgumentException ie ) { throw new RuntimeException ( "IndexType '" + indexTypeAsString + "' is unsupported." , ie ) ; } } if ( indexType == null ) { throw new RuntimeException ( "IndexType '" + indexTypeAsString + "' is unsupported." ) ; } return indexType ; } | Getting IndexType object from indexType string | 156 | 8 |
12,209 | private ByteBuffer subColumnNameAsBytes ( String superColumn , String columnFamily ) { CfDef columnFamilyDef = getCfDef ( columnFamily ) ; return subColumnNameAsBytes ( superColumn , columnFamilyDef ) ; } | Converts sub - column name into ByteBuffer according to comparator type | 49 | 14 |
12,210 | private ByteBuffer subColumnNameAsBytes ( String superColumn , CfDef columnFamilyDef ) { String comparatorClass = columnFamilyDef . subcomparator_type ; if ( comparatorClass == null ) { sessionState . out . println ( String . format ( "Notice: defaulting to BytesType subcomparator for '%s'" , columnFamilyDef . getName ( ) ) ) ; comparatorClass = "BytesType" ; } return getBytesAccordingToType ( superColumn , getFormatType ( comparatorClass ) ) ; } | Converts column name into ByteBuffer according to comparator type | 117 | 12 |
12,211 | private AbstractType < ? > getValidatorForValue ( CfDef cfDef , byte [ ] columnNameInBytes ) { String defaultValidator = cfDef . default_validation_class ; for ( ColumnDef columnDefinition : cfDef . getColumn_metadata ( ) ) { byte [ ] nameInBytes = columnDefinition . getName ( ) ; if ( Arrays . equals ( nameInBytes , columnNameInBytes ) ) { return getFormatType ( columnDefinition . getValidation_class ( ) ) ; } } if ( defaultValidator != null && ! defaultValidator . isEmpty ( ) ) { return getFormatType ( defaultValidator ) ; } return null ; } | Get validator for specific column value | 145 | 7 |
12,212 | public static AbstractType < ? > getTypeByFunction ( String functionName ) { Function function ; try { function = Function . valueOf ( functionName . toUpperCase ( ) ) ; } catch ( IllegalArgumentException e ) { String message = String . format ( "Function '%s' not found. Available functions: %s" , functionName , Function . getFunctionNames ( ) ) ; throw new RuntimeException ( message , e ) ; } return function . getValidator ( ) ; } | Get AbstractType by function name | 106 | 6 |
12,213 | private void updateColumnMetaData ( CfDef columnFamily , ByteBuffer columnName , String validationClass ) { ColumnDef column = getColumnDefByName ( columnFamily , columnName ) ; if ( column != null ) { // if validation class is the same - no need to modify it if ( column . getValidation_class ( ) . equals ( validationClass ) ) return ; // updating column definition with new validation_class column . setValidation_class ( validationClass ) ; } else { List < ColumnDef > columnMetaData = new ArrayList < ColumnDef > ( columnFamily . getColumn_metadata ( ) ) ; columnMetaData . add ( new ColumnDef ( columnName , validationClass ) ) ; columnFamily . setColumn_metadata ( columnMetaData ) ; } } | Used to locally update column family definition with new column metadata | 164 | 11 |
12,214 | private ColumnDef getColumnDefByName ( CfDef columnFamily , ByteBuffer columnName ) { for ( ColumnDef columnDef : columnFamily . getColumn_metadata ( ) ) { byte [ ] currName = columnDef . getName ( ) ; if ( ByteBufferUtil . compare ( currName , columnName ) == 0 ) { return columnDef ; } } return null ; } | Get specific ColumnDef in column family meta data by column name | 83 | 12 |
12,215 | private String formatSubcolumnName ( String keyspace , String columnFamily , ByteBuffer name ) { return getFormatType ( getCfDef ( keyspace , columnFamily ) . subcomparator_type ) . getString ( name ) ; } | returns sub - column name in human - readable format | 52 | 11 |
12,216 | private String formatColumnName ( String keyspace , String columnFamily , ByteBuffer name ) { return getFormatType ( getCfDef ( keyspace , columnFamily ) . comparator_type ) . getString ( name ) ; } | retuns column name in human - readable format | 49 | 9 |
12,217 | private void elapsedTime ( long startTime ) { /** time elapsed in nanoseconds */ long eta = System . nanoTime ( ) - startTime ; sessionState . out . print ( "Elapsed time: " ) ; if ( eta < 10000000 ) { sessionState . out . print ( Math . round ( eta / 10000.0 ) / 100.0 ) ; } else { sessionState . out . print ( Math . round ( eta / 1000000.0 ) ) ; } sessionState . out . println ( " msec(s)." ) ; } | Print elapsed time . Print 2 fraction digits if eta is under 10 ms . | 121 | 16 |
12,218 | public void seek ( long pos ) throws IOException { long inSegmentPos = pos - segmentOffset ; if ( inSegmentPos < 0 || inSegmentPos > buffer . capacity ( ) ) throw new IOException ( String . format ( "Seek position %d is not within mmap segment (seg offs: %d, length: %d)" , pos , segmentOffset , buffer . capacity ( ) ) ) ; seekInternal ( ( int ) inSegmentPos ) ; } | IOException otherwise . | 104 | 4 |
12,219 | @ Override public void index ( ByteBuffer key , ColumnFamily columnFamily ) { Log . debug ( "Indexing row %s in index %s " , key , logName ) ; lock . readLock ( ) . lock ( ) ; try { if ( rowService != null ) { long timestamp = System . currentTimeMillis ( ) ; rowService . index ( key , columnFamily , timestamp ) ; } } catch ( RuntimeException e ) { Log . error ( "Error while indexing row %s" , key ) ; throw e ; } finally { lock . readLock ( ) . unlock ( ) ; } } | Index the given row . | 130 | 5 |
12,220 | @ Override public void delete ( DecoratedKey key , OpOrder . Group opGroup ) { Log . debug ( "Removing row %s from index %s" , key , logName ) ; lock . writeLock ( ) . lock ( ) ; try { rowService . delete ( key ) ; rowService = null ; } catch ( RuntimeException e ) { Log . error ( e , "Error deleting row %s" , key ) ; throw e ; } finally { lock . writeLock ( ) . unlock ( ) ; } } | cleans up deleted columns from cassandra cleanup compaction | 113 | 11 |
12,221 | public void sendTreeRequests ( Collection < InetAddress > endpoints ) { // send requests to all nodes List < InetAddress > allEndpoints = new ArrayList <> ( endpoints ) ; allEndpoints . add ( FBUtilities . getBroadcastAddress ( ) ) ; // Create a snapshot at all nodes unless we're using pure parallel repairs if ( parallelismDegree != RepairParallelism . PARALLEL ) { List < ListenableFuture < InetAddress >> snapshotTasks = new ArrayList <> ( allEndpoints . size ( ) ) ; for ( InetAddress endpoint : allEndpoints ) { SnapshotTask snapshotTask = new SnapshotTask ( desc , endpoint ) ; snapshotTasks . add ( snapshotTask ) ; taskExecutor . execute ( snapshotTask ) ; } ListenableFuture < List < InetAddress > > allSnapshotTasks = Futures . allAsList ( snapshotTasks ) ; // Execute send tree request after all snapshot complete Futures . addCallback ( allSnapshotTasks , new FutureCallback < List < InetAddress > > ( ) { public void onSuccess ( List < InetAddress > endpoints ) { sendTreeRequestsInternal ( endpoints ) ; } public void onFailure ( Throwable throwable ) { // TODO need to propagate error to RepairSession logger . error ( "Error occurred during snapshot phase" , throwable ) ; listener . failedSnapshot ( ) ; failed = true ; } } , taskExecutor ) ; } else { sendTreeRequestsInternal ( allEndpoints ) ; } } | Send merkle tree request to every involved neighbor . | 336 | 11 |
12,222 | public synchronized int addTree ( InetAddress endpoint , MerkleTree tree ) { // Wait for all request to have been performed (see #3400) try { requestsSent . await ( ) ; } catch ( InterruptedException e ) { throw new AssertionError ( "Interrupted while waiting for requests to be sent" ) ; } if ( tree == null ) failed = true ; else trees . add ( new TreeResponse ( endpoint , tree ) ) ; return treeRequests . completed ( endpoint ) ; } | Add a new received tree and return the number of remaining tree to be received for the job to be complete . | 108 | 22 |
12,223 | public String getString ( ByteBuffer bytes ) { TypeSerializer < T > serializer = getSerializer ( ) ; serializer . validate ( bytes ) ; return serializer . toString ( serializer . deserialize ( bytes ) ) ; } | get a string representation of the bytes suitable for log messages | 52 | 11 |
12,224 | public boolean isValueCompatibleWith ( AbstractType < ? > otherType ) { return isValueCompatibleWithInternal ( ( otherType instanceof ReversedType ) ? ( ( ReversedType ) otherType ) . baseType : otherType ) ; } | Returns true if values of the other AbstractType can be read and reasonably interpreted by the this AbstractType . Note that this is a weaker version of isCompatibleWith as it does not require that both type compare values the same way . | 55 | 47 |
12,225 | public int compareCollectionMembers ( ByteBuffer v1 , ByteBuffer v2 , ByteBuffer collectionName ) { return compare ( v1 , v2 ) ; } | An alternative comparison function used by CollectionsType in conjunction with CompositeType . | 33 | 14 |
12,226 | private static void writeKey ( PrintStream out , String value ) { writeJSON ( out , value ) ; out . print ( ": " ) ; } | JSON Hash Key serializer | 32 | 5 |
12,227 | private static List < Object > serializeColumn ( Cell cell , CFMetaData cfMetaData ) { CellNameType comparator = cfMetaData . comparator ; ArrayList < Object > serializedColumn = new ArrayList < Object > ( ) ; serializedColumn . add ( comparator . getString ( cell . name ( ) ) ) ; if ( cell instanceof DeletedCell ) { serializedColumn . add ( cell . getLocalDeletionTime ( ) ) ; } else { AbstractType < ? > validator = cfMetaData . getValueValidator ( cell . name ( ) ) ; serializedColumn . add ( validator . getString ( cell . value ( ) ) ) ; } serializedColumn . add ( cell . timestamp ( ) ) ; if ( cell instanceof DeletedCell ) { serializedColumn . add ( "d" ) ; } else if ( cell instanceof ExpiringCell ) { serializedColumn . add ( "e" ) ; serializedColumn . add ( ( ( ExpiringCell ) cell ) . getTimeToLive ( ) ) ; serializedColumn . add ( cell . getLocalDeletionTime ( ) ) ; } else if ( cell instanceof CounterCell ) { serializedColumn . add ( "c" ) ; serializedColumn . add ( ( ( CounterCell ) cell ) . timestampOfLastDelete ( ) ) ; } return serializedColumn ; } | Serialize a given cell to a List of Objects that jsonMapper knows how to turn into strings . Format is | 297 | 23 |
12,228 | private static void serializeRow ( SSTableIdentityIterator row , DecoratedKey key , PrintStream out ) { serializeRow ( row . getColumnFamily ( ) . deletionInfo ( ) , row , row . getColumnFamily ( ) . metadata ( ) , key , out ) ; } | Get portion of the columns and serialize in loop while not more columns left in the row | 63 | 18 |
12,229 | public static void enumeratekeys ( Descriptor desc , PrintStream outs , CFMetaData metadata ) throws IOException { KeyIterator iter = new KeyIterator ( desc ) ; try { DecoratedKey lastKey = null ; while ( iter . hasNext ( ) ) { DecoratedKey key = iter . next ( ) ; // validate order of the keys in the sstable if ( lastKey != null && lastKey . compareTo ( key ) > 0 ) throw new IOException ( "Key out of order! " + lastKey + " > " + key ) ; lastKey = key ; outs . println ( metadata . getKeyValidator ( ) . getString ( key . getKey ( ) ) ) ; checkStream ( outs ) ; // flushes } } finally { iter . close ( ) ; } } | Enumerate row keys from an SSTableReader and write the result to a PrintStream . | 171 | 20 |
12,230 | public static void export ( Descriptor desc , PrintStream outs , Collection < String > toExport , String [ ] excludes , CFMetaData metadata ) throws IOException { SSTableReader sstable = SSTableReader . open ( desc ) ; RandomAccessReader dfile = sstable . openDataReader ( ) ; try { IPartitioner partitioner = sstable . partitioner ; if ( excludes != null ) toExport . removeAll ( Arrays . asList ( excludes ) ) ; outs . println ( "[" ) ; int i = 0 ; // last key to compare order DecoratedKey lastKey = null ; for ( String key : toExport ) { DecoratedKey decoratedKey = partitioner . decorateKey ( metadata . getKeyValidator ( ) . fromString ( key ) ) ; if ( lastKey != null && lastKey . compareTo ( decoratedKey ) > 0 ) throw new IOException ( "Key out of order! " + lastKey + " > " + decoratedKey ) ; lastKey = decoratedKey ; RowIndexEntry entry = sstable . getPosition ( decoratedKey , SSTableReader . Operator . EQ ) ; if ( entry == null ) continue ; dfile . seek ( entry . position ) ; ByteBufferUtil . readWithShortLength ( dfile ) ; // row key DeletionInfo deletionInfo = new DeletionInfo ( DeletionTime . serializer . deserialize ( dfile ) ) ; Iterator < OnDiskAtom > atomIterator = sstable . metadata . getOnDiskIterator ( dfile , sstable . descriptor . version ) ; checkStream ( outs ) ; if ( i != 0 ) outs . println ( "," ) ; i ++ ; serializeRow ( deletionInfo , atomIterator , sstable . metadata , decoratedKey , outs ) ; } outs . println ( "\n]" ) ; outs . flush ( ) ; } finally { dfile . close ( ) ; } } | Export specific rows from an SSTable and write the resulting JSON to a PrintStream . | 413 | 18 |
12,231 | static void export ( SSTableReader reader , PrintStream outs , String [ ] excludes , CFMetaData metadata ) throws IOException { Set < String > excludeSet = new HashSet < String > ( ) ; if ( excludes != null ) excludeSet = new HashSet < String > ( Arrays . asList ( excludes ) ) ; SSTableIdentityIterator row ; ISSTableScanner scanner = reader . getScanner ( ) ; try { outs . println ( "[" ) ; int i = 0 ; // collecting keys to export while ( scanner . hasNext ( ) ) { row = ( SSTableIdentityIterator ) scanner . next ( ) ; String currentKey = row . getColumnFamily ( ) . metadata ( ) . getKeyValidator ( ) . getString ( row . getKey ( ) . getKey ( ) ) ; if ( excludeSet . contains ( currentKey ) ) continue ; else if ( i != 0 ) outs . println ( "," ) ; serializeRow ( row , row . getKey ( ) , outs ) ; checkStream ( outs ) ; i ++ ; } outs . println ( "\n]" ) ; outs . flush ( ) ; } finally { scanner . close ( ) ; } } | than once from within the same process . | 258 | 8 |
12,232 | public static void export ( Descriptor desc , PrintStream outs , String [ ] excludes , CFMetaData metadata ) throws IOException { export ( SSTableReader . open ( desc ) , outs , excludes , metadata ) ; } | Export an SSTable and write the resulting JSON to a PrintStream . | 48 | 15 |
12,233 | public static void export ( Descriptor desc , String [ ] excludes , CFMetaData metadata ) throws IOException { export ( desc , System . out , excludes , metadata ) ; } | Export an SSTable and write the resulting JSON to standard out . | 38 | 14 |
12,234 | public static void main ( String [ ] args ) throws ConfigurationException { String usage = String . format ( "Usage: %s <sstable> [-k key [-k key [...]] -x key [-x key [...]]]%n" , SSTableExport . class . getName ( ) ) ; CommandLineParser parser = new PosixParser ( ) ; try { cmd = parser . parse ( options , args ) ; } catch ( ParseException e1 ) { System . err . println ( e1 . getMessage ( ) ) ; System . err . println ( usage ) ; System . exit ( 1 ) ; } if ( cmd . getArgs ( ) . length != 1 ) { System . err . println ( "You must supply exactly one sstable" ) ; System . err . println ( usage ) ; System . exit ( 1 ) ; } String [ ] keys = cmd . getOptionValues ( KEY_OPTION ) ; String [ ] excludes = cmd . getOptionValues ( EXCLUDEKEY_OPTION ) ; String ssTableFileName = new File ( cmd . getArgs ( ) [ 0 ] ) . getAbsolutePath ( ) ; DatabaseDescriptor . loadSchemas ( false ) ; Descriptor descriptor = Descriptor . fromFilename ( ssTableFileName ) ; // Start by validating keyspace name if ( Schema . instance . getKSMetaData ( descriptor . ksname ) == null ) { System . err . println ( String . format ( "Filename %s references to nonexistent keyspace: %s!" , ssTableFileName , descriptor . ksname ) ) ; System . exit ( 1 ) ; } Keyspace keyspace = Keyspace . open ( descriptor . ksname ) ; // Make it works for indexes too - find parent cf if necessary String baseName = descriptor . cfname ; if ( descriptor . cfname . contains ( "." ) ) { String [ ] parts = descriptor . cfname . split ( "\\." , 2 ) ; baseName = parts [ 0 ] ; } // IllegalArgumentException will be thrown here if ks/cf pair does not exist ColumnFamilyStore cfStore = null ; try { cfStore = keyspace . getColumnFamilyStore ( baseName ) ; } catch ( IllegalArgumentException e ) { System . err . println ( String . format ( "The provided column family is not part of this cassandra keyspace: keyspace = %s, column family = %s" , descriptor . ksname , descriptor . cfname ) ) ; System . exit ( 1 ) ; } try { if ( cmd . hasOption ( ENUMERATEKEYS_OPTION ) ) { enumeratekeys ( descriptor , System . out , cfStore . metadata ) ; } else { if ( ( keys != null ) && ( keys . length > 0 ) ) export ( descriptor , System . out , Arrays . asList ( keys ) , excludes , cfStore . metadata ) ; else export ( descriptor , excludes , cfStore . metadata ) ; } } catch ( IOException e ) { // throwing exception outside main with broken pipe causes windows cmd to hang e . printStackTrace ( System . err ) ; } System . exit ( 0 ) ; } | Given arguments specifying an SSTable and optionally an output file export the contents of the SSTable to JSON . | 681 | 23 |
12,235 | public SemanticVersion findSupportingVersion ( SemanticVersion ... versions ) { for ( SemanticVersion version : versions ) { if ( isSupportedBy ( version ) ) return version ; } return null ; } | Returns a version that is backward compatible with this version amongst a list of provided version or null if none can be found . | 43 | 24 |
12,236 | private Pair < List < SSTableReader > , Multimap < DataTracker , SSTableReader > > getCompactingAndNonCompactingSSTables ( ) { List < SSTableReader > allCompacting = new ArrayList <> ( ) ; Multimap < DataTracker , SSTableReader > allNonCompacting = HashMultimap . create ( ) ; for ( Keyspace ks : Keyspace . all ( ) ) { for ( ColumnFamilyStore cfStore : ks . getColumnFamilyStores ( ) ) { Set < SSTableReader > nonCompacting , allSSTables ; do { allSSTables = cfStore . getDataTracker ( ) . getSSTables ( ) ; nonCompacting = Sets . newHashSet ( cfStore . getDataTracker ( ) . getUncompactingSSTables ( allSSTables ) ) ; } while ( ! ( nonCompacting . isEmpty ( ) || cfStore . getDataTracker ( ) . markCompacting ( nonCompacting ) ) ) ; allNonCompacting . putAll ( cfStore . getDataTracker ( ) , nonCompacting ) ; allCompacting . addAll ( Sets . difference ( allSSTables , nonCompacting ) ) ; } } return Pair . create ( allCompacting , allNonCompacting ) ; } | Returns a Pair of all compacting and non - compacting sstables . Non - compacting sstables will be marked as compacting . | 286 | 30 |
12,237 | @ VisibleForTesting public static List < SSTableReader > redistributeSummaries ( List < SSTableReader > compacting , List < SSTableReader > nonCompacting , long memoryPoolBytes ) throws IOException { long total = 0 ; for ( SSTableReader sstable : Iterables . concat ( compacting , nonCompacting ) ) total += sstable . getIndexSummaryOffHeapSize ( ) ; List < SSTableReader > oldFormatSSTables = new ArrayList <> ( ) ; for ( SSTableReader sstable : nonCompacting ) { // We can't change the sampling level of sstables with the old format, because the serialization format // doesn't include the sampling level. Leave this one as it is. (See CASSANDRA-8993 for details.) logger . trace ( "SSTable {} cannot be re-sampled due to old sstable format" , sstable ) ; if ( ! sstable . descriptor . version . hasSamplingLevel ) oldFormatSSTables . add ( sstable ) ; } nonCompacting . removeAll ( oldFormatSSTables ) ; logger . debug ( "Beginning redistribution of index summaries for {} sstables with memory pool size {} MB; current spaced used is {} MB" , nonCompacting . size ( ) , memoryPoolBytes / 1024L / 1024L , total / 1024.0 / 1024.0 ) ; final Map < SSTableReader , Double > readRates = new HashMap <> ( nonCompacting . size ( ) ) ; double totalReadsPerSec = 0.0 ; for ( SSTableReader sstable : nonCompacting ) { if ( sstable . getReadMeter ( ) != null ) { Double readRate = sstable . getReadMeter ( ) . fifteenMinuteRate ( ) ; totalReadsPerSec += readRate ; readRates . put ( sstable , readRate ) ; } } logger . trace ( "Total reads/sec across all sstables in index summary resize process: {}" , totalReadsPerSec ) ; // copy and sort by read rates (ascending) List < SSTableReader > sstablesByHotness = new ArrayList <> ( nonCompacting ) ; Collections . sort ( sstablesByHotness , new ReadRateComparator ( readRates ) ) ; long remainingBytes = memoryPoolBytes ; for ( SSTableReader sstable : Iterables . concat ( compacting , oldFormatSSTables ) ) remainingBytes -= sstable . getIndexSummaryOffHeapSize ( ) ; logger . trace ( "Index summaries for compacting SSTables are using {} MB of space" , ( memoryPoolBytes - remainingBytes ) / 1024.0 / 1024.0 ) ; List < SSTableReader > newSSTables = adjustSamplingLevels ( sstablesByHotness , totalReadsPerSec , remainingBytes ) ; total = 0 ; for ( SSTableReader sstable : Iterables . concat ( compacting , oldFormatSSTables , newSSTables ) ) total += sstable . getIndexSummaryOffHeapSize ( ) ; logger . debug ( "Completed resizing of index summaries; current approximate memory used: {} MB" , total / 1024.0 / 1024.0 ) ; return newSSTables ; } | Attempts to fairly distribute a fixed pool of memory for index summaries across a set of SSTables based on their recent read rates . | 722 | 27 |
12,238 | public ByteBuffer getByteBuffer ( ) throws InvalidRequestException { switch ( type ) { case STRING : return AsciiType . instance . fromString ( text ) ; case INTEGER : return IntegerType . instance . fromString ( text ) ; case UUID : // we specifically want the Lexical class here, not "UUIDType," because we're supposed to have // a uuid-shaped string here, and UUIDType also accepts integer or date strings (and turns them into version 1 uuids). return LexicalUUIDType . instance . fromString ( text ) ; case FLOAT : return FloatType . instance . fromString ( text ) ; } // FIXME: handle scenario that should never happen return null ; } | Returns the typed value serialized to a ByteBuffer . | 156 | 11 |
12,239 | private boolean selfAssign ( ) { // if we aren't permitted to assign in this state, fail if ( ! get ( ) . canAssign ( true ) ) return false ; for ( SEPExecutor exec : pool . executors ) { if ( exec . takeWorkPermit ( true ) ) { Work work = new Work ( exec ) ; // we successfully started work on this executor, so we must either assign it to ourselves or ... if ( assign ( work , true ) ) return true ; // ... if we fail, schedule it to another worker pool . schedule ( work ) ; // and return success as we must have already been assigned a task assert get ( ) . assigned != null ; return true ; } } return false ; } | try to assign ourselves an executor with work available | 155 | 10 |
12,240 | private void startSpinning ( ) { assert get ( ) == Work . WORKING ; pool . spinningCount . incrementAndGet ( ) ; set ( Work . SPINNING ) ; } | collection at the same time | 39 | 5 |
12,241 | private void doWaitSpin ( ) { // pick a random sleep interval based on the number of threads spinning, so that // we should always have a thread about to wake up, but most threads are sleeping long sleep = 10000L * pool . spinningCount . get ( ) ; sleep = Math . min ( 1000000 , sleep ) ; sleep *= Math . random ( ) ; sleep = Math . max ( 10000 , sleep ) ; long start = System . nanoTime ( ) ; // place ourselves in the spinning collection; if we clash with another thread just exit Long target = start + sleep ; if ( pool . spinning . putIfAbsent ( target , this ) != null ) return ; LockSupport . parkNanos ( sleep ) ; // remove ourselves (if haven't been already) - we should be at or near the front, so should be cheap-ish pool . spinning . remove ( target , this ) ; // finish timing and grab spinningTime (before we finish timing so it is under rather than overestimated) long end = System . nanoTime ( ) ; long spin = end - start ; long stopCheck = pool . stopCheck . addAndGet ( spin ) ; maybeStop ( stopCheck , end ) ; if ( prevStopCheck + spin == stopCheck ) soleSpinnerSpinTime += spin ; else soleSpinnerSpinTime = 0 ; prevStopCheck = stopCheck ; } | perform a sleep - spin incrementing pool . stopCheck accordingly | 290 | 13 |
12,242 | private void maybeStop ( long stopCheck , long now ) { long delta = now - stopCheck ; if ( delta <= 0 ) { // if stopCheck has caught up with present, we've been spinning too much, so if we can atomically // set it to the past again, we should stop a worker if ( pool . stopCheck . compareAndSet ( stopCheck , now - stopCheckInterval ) ) { // try and stop ourselves; // if we've already been assigned work stop another worker if ( ! assign ( Work . STOP_SIGNALLED , true ) ) pool . schedule ( Work . STOP_SIGNALLED ) ; } } else if ( soleSpinnerSpinTime > stopCheckInterval && pool . spinningCount . get ( ) == 1 ) { // permit self-stopping assign ( Work . STOP_SIGNALLED , true ) ; } else { // if stop check has gotten too far behind present, update it so new spins can affect it while ( delta > stopCheckInterval * 2 && ! pool . stopCheck . compareAndSet ( stopCheck , now - stopCheckInterval ) ) { stopCheck = pool . stopCheck . get ( ) ; delta = now - stopCheck ; } } } | realtime we have spun too much and deschedule ; if we get too far behind realtime we reset to our initial offset | 258 | 26 |
12,243 | public List < Row > postReconciliationProcessing ( List < IndexExpression > clause , List < Row > rows ) { return rows ; } | Combines index query results from multiple nodes . This is done by the coordinator node after it has reconciled the replica responses . | 32 | 25 |
12,244 | public boolean isIndexBuilt ( ByteBuffer columnName ) { return SystemKeyspace . isIndexBuilt ( baseCfs . keyspace . getName ( ) , getNameForSystemKeyspace ( columnName ) ) ; } | Checks if the index for specified column is fully built | 46 | 11 |
12,245 | protected void buildIndexBlocking ( ) { logger . info ( String . format ( "Submitting index build of %s for data in %s" , getIndexName ( ) , StringUtils . join ( baseCfs . getSSTables ( ) , ", " ) ) ) ; try ( Refs < SSTableReader > sstables = baseCfs . selectAndReference ( ColumnFamilyStore . CANONICAL_SSTABLES ) . refs ) { SecondaryIndexBuilder builder = new SecondaryIndexBuilder ( baseCfs , Collections . singleton ( getIndexName ( ) ) , new ReducingKeyIterator ( sstables ) ) ; Future < ? > future = CompactionManager . instance . submitIndexBuild ( builder ) ; FBUtilities . waitOnFuture ( future ) ; forceBlockingFlush ( ) ; setIndexBuilt ( ) ; } logger . info ( "Index build of {} complete" , getIndexName ( ) ) ; } | Builds the index using the data in the underlying CFS Blocks till it s complete | 204 | 17 |
12,246 | public Future < ? > buildIndexAsync ( ) { // if we're just linking in the index to indexedColumns on an already-built index post-restart, we're done boolean allAreBuilt = true ; for ( ColumnDefinition cdef : columnDefs ) { if ( ! SystemKeyspace . isIndexBuilt ( baseCfs . keyspace . getName ( ) , getNameForSystemKeyspace ( cdef . name . bytes ) ) ) { allAreBuilt = false ; break ; } } if ( allAreBuilt ) return null ; // build it asynchronously; addIndex gets called by CFS open and schema update, neither of which // we want to block for a long period. (actual build is serialized on CompactionManager.) Runnable runnable = new Runnable ( ) { public void run ( ) { baseCfs . forceBlockingFlush ( ) ; buildIndexBlocking ( ) ; } } ; FutureTask < ? > f = new FutureTask < Object > ( runnable , null ) ; new Thread ( f , "Creating index: " + getIndexName ( ) ) . start ( ) ; return f ; } | Builds the index using the data in the underlying CF non blocking | 248 | 13 |
12,247 | public DecoratedKey getIndexKeyFor ( ByteBuffer value ) { // FIXME: this imply one column definition per index ByteBuffer name = columnDefs . iterator ( ) . next ( ) . name . bytes ; return new BufferDecoratedKey ( new LocalToken ( baseCfs . metadata . getColumnDefinition ( name ) . type , value ) , value ) ; } | Returns the decoratedKey for a column value | 80 | 8 |
12,248 | public static SecondaryIndex createInstance ( ColumnFamilyStore baseCfs , ColumnDefinition cdef ) throws ConfigurationException { SecondaryIndex index ; switch ( cdef . getIndexType ( ) ) { case KEYS : index = new KeysIndex ( ) ; break ; case COMPOSITES : index = CompositesIndex . create ( cdef ) ; break ; case CUSTOM : assert cdef . getIndexOptions ( ) != null ; String class_name = cdef . getIndexOptions ( ) . get ( CUSTOM_INDEX_OPTION_NAME ) ; assert class_name != null ; try { index = ( SecondaryIndex ) Class . forName ( class_name ) . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } break ; default : throw new RuntimeException ( "Unknown index type: " + cdef . getIndexName ( ) ) ; } index . addColumnDef ( cdef ) ; index . validateOptions ( ) ; index . setBaseCfs ( baseCfs ) ; return index ; } | This is the primary way to create a secondary index instance for a CF column . It will validate the index_options before initializing . | 225 | 27 |
12,249 | public static CellNameType getIndexComparator ( CFMetaData baseMetadata , ColumnDefinition cdef ) { switch ( cdef . getIndexType ( ) ) { case KEYS : return new SimpleDenseCellNameType ( keyComparator ) ; case COMPOSITES : return CompositesIndex . getIndexComparator ( baseMetadata , cdef ) ; case CUSTOM : return null ; } throw new AssertionError ( ) ; } | Returns the index comparator for index backed by CFS or null . | 96 | 14 |
12,250 | public RepairFuture submitRepairSession ( UUID parentRepairSession , Range < Token > range , String keyspace , RepairParallelism parallelismDegree , Set < InetAddress > endpoints , String ... cfnames ) { if ( cfnames . length == 0 ) return null ; RepairSession session = new RepairSession ( parentRepairSession , range , keyspace , parallelismDegree , endpoints , cfnames ) ; if ( session . endpoints . isEmpty ( ) ) return null ; RepairFuture futureTask = new RepairFuture ( session ) ; executor . execute ( futureTask ) ; return futureTask ; } | Requests repairs for the given keyspace and column families . | 134 | 12 |
12,251 | public static Set < InetAddress > getNeighbors ( String keyspaceName , Range < Token > toRepair , Collection < String > dataCenters , Collection < String > hosts ) { StorageService ss = StorageService . instance ; Map < Range < Token > , List < InetAddress > > replicaSets = ss . getRangeToAddressMap ( keyspaceName ) ; Range < Token > rangeSuperSet = null ; for ( Range < Token > range : ss . getLocalRanges ( keyspaceName ) ) { if ( range . contains ( toRepair ) ) { rangeSuperSet = range ; break ; } else if ( range . intersects ( toRepair ) ) { throw new IllegalArgumentException ( "Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair" ) ; } } if ( rangeSuperSet == null || ! replicaSets . containsKey ( rangeSuperSet ) ) return Collections . emptySet ( ) ; Set < InetAddress > neighbors = new HashSet <> ( replicaSets . get ( rangeSuperSet ) ) ; neighbors . remove ( FBUtilities . getBroadcastAddress ( ) ) ; if ( dataCenters != null ) { TokenMetadata . Topology topology = ss . getTokenMetadata ( ) . cloneOnlyTokenMap ( ) . getTopology ( ) ; Set < InetAddress > dcEndpoints = Sets . newHashSet ( ) ; Multimap < String , InetAddress > dcEndpointsMap = topology . getDatacenterEndpoints ( ) ; for ( String dc : dataCenters ) { Collection < InetAddress > c = dcEndpointsMap . get ( dc ) ; if ( c != null ) dcEndpoints . addAll ( c ) ; } return Sets . intersection ( neighbors , dcEndpoints ) ; } else if ( hosts != null ) { Set < InetAddress > specifiedHost = new HashSet <> ( ) ; for ( final String host : hosts ) { try { final InetAddress endpoint = InetAddress . getByName ( host . trim ( ) ) ; if ( endpoint . equals ( FBUtilities . getBroadcastAddress ( ) ) || neighbors . contains ( endpoint ) ) specifiedHost . add ( endpoint ) ; } catch ( UnknownHostException e ) { throw new IllegalArgumentException ( "Unknown host specified " + host , e ) ; } } if ( ! specifiedHost . contains ( FBUtilities . getBroadcastAddress ( ) ) ) throw new IllegalArgumentException ( "The current host must be part of the repair" ) ; if ( specifiedHost . size ( ) <= 1 ) { String msg = "Repair requires at least two endpoints that are neighbours before it can continue, the endpoint used for this repair is %s, " + "other available neighbours are %s but these neighbours were not part of the supplied list of hosts to use during the repair (%s)." ; throw new IllegalArgumentException ( String . format ( msg , specifiedHost , neighbors , hosts ) ) ; } specifiedHost . remove ( FBUtilities . getBroadcastAddress ( ) ) ; return specifiedHost ; } return neighbors ; } | Return all of the neighbors with whom we share the provided range . | 677 | 13 |
12,252 | private static String decodeString ( ByteBuffer src ) throws CharacterCodingException { // the decoder needs to be reset every time we use it, hence the copy per thread CharsetDecoder theDecoder = decoder . get ( ) ; theDecoder . reset ( ) ; final CharBuffer dst = CharBuffer . allocate ( ( int ) ( ( double ) src . remaining ( ) * theDecoder . maxCharsPerByte ( ) ) ) ; CoderResult cr = theDecoder . decode ( src , dst , true ) ; if ( ! cr . isUnderflow ( ) ) cr . throwException ( ) ; cr = theDecoder . flush ( dst ) ; if ( ! cr . isUnderflow ( ) ) cr . throwException ( ) ; return dst . flip ( ) . toString ( ) ; } | is resolved in a release used by Cassandra . | 174 | 9 |
12,253 | public void activate ( ) { String pidFile = System . getProperty ( "cassandra-pidfile" ) ; try { try { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; mbs . registerMBean ( new StandardMBean ( new NativeAccess ( ) , NativeAccessMBean . class ) , new ObjectName ( MBEAN_NAME ) ) ; } catch ( Exception e ) { logger . error ( "error registering MBean {}" , MBEAN_NAME , e ) ; //Allow the server to start even if the bean can't be registered } setup ( ) ; if ( pidFile != null ) { new File ( pidFile ) . deleteOnExit ( ) ; } if ( System . getProperty ( "cassandra-foreground" ) == null ) { System . out . close ( ) ; System . err . close ( ) ; } start ( ) ; } catch ( Throwable e ) { logger . error ( "Exception encountered during startup" , e ) ; // try to warn user on stdout too, if we haven't already detached e . printStackTrace ( ) ; System . out . println ( "Exception encountered during startup: " + e . getMessage ( ) ) ; System . exit ( 3 ) ; } } | A convenience method to initialize and start the daemon in one shot . | 278 | 13 |
12,254 | protected static String toInternalName ( String name , boolean keepCase ) { return keepCase ? name : name . toLowerCase ( Locale . US ) ; } | Converts the specified name into the name used internally . | 34 | 11 |
12,255 | public Node < E > append ( E value , int maxSize ) { Node < E > newTail = new Node <> ( randomLevel ( ) , value ) ; lock . writeLock ( ) . lock ( ) ; try { if ( size >= maxSize ) return null ; size ++ ; Node < E > tail = head ; for ( int i = maxHeight - 1 ; i >= newTail . height ( ) ; i -- ) { Node < E > next ; while ( ( next = tail . next ( i ) ) != null ) tail = next ; tail . size [ i ] ++ ; } for ( int i = newTail . height ( ) - 1 ; i >= 0 ; i -- ) { Node < E > next ; while ( ( next = tail . next ( i ) ) != null ) tail = next ; tail . setNext ( i , newTail ) ; newTail . setPrev ( i , tail ) ; } return newTail ; } finally { lock . writeLock ( ) . unlock ( ) ; } } | regardless of its future position in the list from other modifications | 222 | 12 |
12,256 | public void remove ( Node < E > node ) { lock . writeLock ( ) . lock ( ) ; assert node . value != null ; node . value = null ; try { size -- ; // go up through each level in the skip list, unlinking this node; this entails // simply linking each neighbour to each other, and appending the size of the // current level owned by this node's index to the preceding neighbour (since // ownership is defined as any node that you must visit through the index, // removal of ourselves from a level means the preceding index entry is the // entry point to all of the removed node's descendants) for ( int i = 0 ; i < node . height ( ) ; i ++ ) { Node < E > prev = node . prev ( i ) ; Node < E > next = node . next ( i ) ; assert prev != null ; prev . setNext ( i , next ) ; if ( next != null ) next . setPrev ( i , prev ) ; prev . size [ i ] += node . size [ i ] - 1 ; } // then go up the levels, removing 1 from the size at each height above ours for ( int i = node . height ( ) ; i < maxHeight ; i ++ ) { // if we're at our height limit, we backtrack at our top level until we // hit a neighbour with a greater height while ( i == node . height ( ) ) node = node . prev ( i - 1 ) ; node . size [ i ] -- ; } } finally { lock . writeLock ( ) . unlock ( ) ; } } | remove the provided node and its associated value from the list | 332 | 11 |
12,257 | public E get ( int index ) { lock . readLock ( ) . lock ( ) ; try { if ( index >= size ) return null ; index ++ ; int c = 0 ; Node < E > finger = head ; for ( int i = maxHeight - 1 ; i >= 0 ; i -- ) { while ( c + finger . size [ i ] <= index ) { c += finger . size [ i ] ; finger = finger . next ( i ) ; } } assert c == index ; return finger . value ; } finally { lock . readLock ( ) . unlock ( ) ; } } | retrieve the item at the provided index or return null if the index is past the end of the list | 124 | 21 |
12,258 | private boolean isWellFormed ( ) { for ( int i = 0 ; i < maxHeight ; i ++ ) { int c = 0 ; for ( Node node = head ; node != null ; node = node . next ( i ) ) { if ( node . prev ( i ) != null && node . prev ( i ) . next ( i ) != node ) return false ; if ( node . next ( i ) != null && node . next ( i ) . prev ( i ) != node ) return false ; c += node . size [ i ] ; if ( i + 1 < maxHeight && node . parent ( i + 1 ) . next ( i + 1 ) == node . next ( i ) ) { if ( node . parent ( i + 1 ) . size [ i + 1 ] != c ) return false ; c = 0 ; } } if ( i == maxHeight - 1 && c != size + 1 ) return false ; } return true ; } | don t create a separate unit test - tools tree doesn t currently warrant them | 201 | 15 |
12,259 | public int binarySearch ( RowPosition key ) { int low = 0 , mid = offsetCount , high = mid - 1 , result = - 1 ; while ( low <= high ) { mid = ( low + high ) >> 1 ; result = - DecoratedKey . compareTo ( partitioner , ByteBuffer . wrap ( getKey ( mid ) ) , key ) ; if ( result > 0 ) { low = mid + 1 ; } else if ( result == 0 ) { return mid ; } else { high = mid - 1 ; } } return - mid - ( result < 0 ? 1 : 2 ) ; } | Harmony s Collections implementation | 128 | 6 |
12,260 | public void reloadClasses ( ) { File triggerDirectory = FBUtilities . cassandraTriggerDir ( ) ; if ( triggerDirectory == null ) return ; customClassLoader = new CustomClassLoader ( parent , triggerDirectory ) ; cachedTriggers . clear ( ) ; } | Reload the triggers which is already loaded Invoking this will update the class loader so new jars can be loaded . | 57 | 23 |
12,261 | private List < Mutation > executeInternal ( ByteBuffer key , ColumnFamily columnFamily ) { Map < String , TriggerDefinition > triggers = columnFamily . metadata ( ) . getTriggers ( ) ; if ( triggers . isEmpty ( ) ) return null ; List < Mutation > tmutations = Lists . newLinkedList ( ) ; Thread . currentThread ( ) . setContextClassLoader ( customClassLoader ) ; try { for ( TriggerDefinition td : triggers . values ( ) ) { ITrigger trigger = cachedTriggers . get ( td . classOption ) ; if ( trigger == null ) { trigger = loadTriggerInstance ( td . classOption ) ; cachedTriggers . put ( td . classOption , trigger ) ; } Collection < Mutation > temp = trigger . augment ( key , columnFamily ) ; if ( temp != null ) tmutations . addAll ( temp ) ; } return tmutations ; } catch ( Exception ex ) { throw new RuntimeException ( String . format ( "Exception while creating trigger on CF with ID: %s" , columnFamily . id ( ) ) , ex ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( parent ) ; } } | Switch class loader before using the triggers for the column family if not loaded them with the custom class loader . | 256 | 21 |
12,262 | private static CharArraySet getDefaultStopwords ( String language ) { switch ( language ) { case "English" : return EnglishAnalyzer . getDefaultStopSet ( ) ; case "French" : return FrenchAnalyzer . getDefaultStopSet ( ) ; case "Spanish" : return SpanishAnalyzer . getDefaultStopSet ( ) ; case "Portuguese" : return PortugueseAnalyzer . getDefaultStopSet ( ) ; case "Italian" : return ItalianAnalyzer . getDefaultStopSet ( ) ; case "Romanian" : return RomanianAnalyzer . getDefaultStopSet ( ) ; case "German" : return GermanAnalyzer . getDefaultStopSet ( ) ; case "Dutch" : return DutchAnalyzer . getDefaultStopSet ( ) ; case "Swedish" : return SwedishAnalyzer . getDefaultStopSet ( ) ; case "Norwegian" : return NorwegianAnalyzer . getDefaultStopSet ( ) ; case "Danish" : return DanishAnalyzer . getDefaultStopSet ( ) ; case "Russian" : return RussianAnalyzer . getDefaultStopSet ( ) ; case "Finnish" : return FinnishAnalyzer . getDefaultStopSet ( ) ; case "Irish" : return IrishAnalyzer . getDefaultStopSet ( ) ; case "Hungarian" : return HungarianAnalyzer . getDefaultStopSet ( ) ; case "Turkish" : return SpanishAnalyzer . getDefaultStopSet ( ) ; case "Armenian" : return SpanishAnalyzer . getDefaultStopSet ( ) ; case "Basque" : return BasqueAnalyzer . getDefaultStopSet ( ) ; case "Catalan" : return CatalanAnalyzer . getDefaultStopSet ( ) ; default : return CharArraySet . EMPTY_SET ; } } | Returns the default stopwords set used by Lucene language analyzer for the specified language . | 371 | 18 |
12,263 | public static void setInputColumns ( Configuration conf , String columns ) { if ( columns == null || columns . isEmpty ( ) ) return ; conf . set ( INPUT_CQL_COLUMNS_CONFIG , columns ) ; } | Set the CQL columns for the input of this job . | 51 | 12 |
12,264 | public static void setInputCQLPageRowSize ( Configuration conf , String cqlPageRowSize ) { if ( cqlPageRowSize == null ) { throw new UnsupportedOperationException ( "cql page row size may not be null" ) ; } conf . set ( INPUT_CQL_PAGE_ROW_SIZE_CONFIG , cqlPageRowSize ) ; } | Set the CQL query Limit for the input of this job . | 83 | 13 |
12,265 | public static void setInputWhereClauses ( Configuration conf , String clauses ) { if ( clauses == null || clauses . isEmpty ( ) ) return ; conf . set ( INPUT_CQL_WHERE_CLAUSE_CONFIG , clauses ) ; } | Set the CQL user defined where clauses for the input of this job . | 53 | 15 |
12,266 | public static void setOutputCql ( Configuration conf , String cql ) { if ( cql == null || cql . isEmpty ( ) ) return ; conf . set ( OUTPUT_CQL , cql ) ; } | Set the CQL prepared statement for the output of this job . | 48 | 13 |
12,267 | public long getTimestamp ( ) { while ( true ) { long current = System . currentTimeMillis ( ) * 1000 ; long last = lastTimestampMicros . get ( ) ; long tstamp = last >= current ? last + 1 : current ; if ( lastTimestampMicros . compareAndSet ( last , tstamp ) ) return tstamp ; } } | This clock guarantees that updates for the same ClientState will be ordered in the sequence seen even if multiple updates happen in the same millisecond . | 81 | 28 |
12,268 | public void login ( AuthenticatedUser user ) throws AuthenticationException { if ( ! user . isAnonymous ( ) && ! Auth . isExistingUser ( user . getName ( ) ) ) throw new AuthenticationException ( String . format ( "User %s doesn't exist - create it with CREATE USER query first" , user . getName ( ) ) ) ; this . user = user ; } | Attempts to login the given user . | 83 | 7 |
12,269 | @ VisibleForTesting protected static boolean notAllowedStrategy ( DockerSlaveTemplate template ) { if ( isNull ( template ) ) { LOG . debug ( "Skipping DockerProvisioningStrategy because: template is null" ) ; return true ; } final RetentionStrategy retentionStrategy = template . getRetentionStrategy ( ) ; if ( isNull ( retentionStrategy ) ) { LOG . debug ( "Skipping DockerProvisioningStrategy because: strategy is null for {}" , template ) ; } if ( retentionStrategy instanceof DockerOnceRetentionStrategy ) { if ( template . getNumExecutors ( ) == 1 ) { LOG . debug ( "Applying faster provisioning for single executor template {}" , template ) ; return false ; } else { LOG . debug ( "Skipping DockerProvisioningStrategy because: numExecutors is {} for {}" , template . getNumExecutors ( ) , template ) ; return true ; } } if ( retentionStrategy instanceof RetentionStrategy . Demand ) { LOG . debug ( "Applying faster provisioning for Demand strategy for template {}" , template ) ; return false ; } // forbid by default LOG . trace ( "Skipping YAD provisioning for unknown mix of configuration for {}" , template ) ; return true ; } | Exclude unknown mix of configuration . | 286 | 7 |
12,270 | public void pullImage ( DockerImagePullStrategy pullStrategy , String imageName ) throws InterruptedException { LOG . info ( "Pulling image {} with {} strategy..." , imageName , pullStrategy ) ; final List < Image > images = getDockerCli ( ) . listImagesCmd ( ) . withShowAll ( true ) . exec ( ) ; NameParser . ReposTag repostag = NameParser . parseRepositoryTag ( imageName ) ; // if image was specified without tag, then treat as latest final String fullImageName = repostag . repos + ":" + ( repostag . tag . isEmpty ( ) ? "latest" : repostag . tag ) ; boolean hasImage = Iterables . any ( images , image -> nonNull ( image . getRepoTags ( ) ) && Arrays . asList ( image . getRepoTags ( ) ) . contains ( fullImageName ) ) ; boolean pull = hasImage ? pullStrategy . pullIfExists ( imageName ) : pullStrategy . pullIfNotExists ( imageName ) ; if ( pull ) { LOG . info ( "Pulling image '{}' {}. This may take awhile..." , imageName , hasImage ? "again" : "since one was not found" ) ; long startTime = System . currentTimeMillis ( ) ; //Identifier amiId = Identifier.fromCompoundString(ami); getDockerCli ( ) . pullImageCmd ( imageName ) . exec ( new PullImageResultCallback ( ) ) . awaitSuccess ( ) ; long pullTime = System . currentTimeMillis ( ) - startTime ; LOG . info ( "Finished pulling image '{}', took {} ms" , imageName , pullTime ) ; } } | Pull docker image on this docker host . | 382 | 8 |
12,271 | public String buildImage ( Map < String , File > plugins ) throws IOException , InterruptedException { LOG . debug ( "Building image for {}" , plugins ) ; // final File tempDirectory = TempFileHelper.createTempDirectory("build-image", targetDir().toPath()); final File buildDir = new File ( targetDir ( ) . getAbsolutePath ( ) + "/docker-it/build-image" ) ; if ( buildDir . exists ( ) ) { deleteDirectory ( buildDir ) ; } if ( ! buildDir . mkdirs ( ) ) { throw new IllegalStateException ( "Can't create temp directory " + buildDir . getAbsolutePath ( ) ) ; } final String dockerfile = generateDockerfileFor ( plugins ) ; final File dockerfileFile = new File ( buildDir , "Dockerfile" ) ; writeStringToFile ( dockerfileFile , dockerfile ) ; final File buildHomePath = new File ( buildDir , JenkinsDockerImage . JENKINS_DEFAULT . homePath ) ; final File jenkinsConfig = new File ( buildHomePath , "config.xml" ) ; DockerHPIContainerUtil . copyResourceFromClass ( DockerHPIContainerUtil . class , "config.xml" , jenkinsConfig ) ; writeStringToFile ( new File ( buildHomePath , "jenkins.install.UpgradeWizard.state" ) , "2.19.4" ) ; writeStringToFile ( new File ( buildHomePath , "jenkins.install.InstallUtil.lastExecVersion" ) , "2.19.4" ) ; final File pluginDir = new File ( buildHomePath , "/plugins/" ) ; if ( ! pluginDir . mkdirs ( ) ) { throw new IllegalStateException ( "Can't create dirs " + pluginDir . getAbsolutePath ( ) ) ; } for ( Map . Entry < String , File > entry : plugins . entrySet ( ) ) { final File dst = new File ( pluginDir + "/" + entry . getKey ( ) ) ; copyFile ( entry . getValue ( ) , dst ) ; } try { LOG . info ( "Building data-image..." ) ; return getDockerCli ( ) . buildImageCmd ( buildDir ) . withTag ( DATA_IMAGE ) . withForcerm ( true ) . exec ( new BuildImageResultCallback ( ) { public void onNext ( BuildResponseItem item ) { String text = item . getStream ( ) ; if ( nonNull ( text ) ) { LOG . debug ( StringUtils . removeEnd ( text , NL ) ) ; } super . onNext ( item ) ; } } ) . awaitImageId ( ) ; } finally { buildDir . delete ( ) ; } } | Build docker image containing specified plugins . | 597 | 7 |
12,272 | public String runFreshJenkinsContainer ( DockerImagePullStrategy pullStrategy , boolean forceRefresh ) throws IOException , SettingsBuildingException , InterruptedException { LOG . debug ( "Entering run fresh jenkins container." ) ; pullImage ( pullStrategy , JENKINS_DEFAULT . getDockerImageName ( ) ) ; // labels attached to container allows cleanup container if it wasn't removed final Map < String , String > labels = new HashMap <> ( ) ; labels . put ( "test.displayName" , description . getDisplayName ( ) ) ; LOG . debug ( "Removing existed container before" ) ; try { final List < Container > containers = getDockerCli ( ) . listContainersCmd ( ) . withShowAll ( true ) . exec ( ) ; for ( Container c : containers ) { if ( c . getLabels ( ) . equals ( labels ) ) { // equals? container labels vs image labels? LOG . debug ( "Removing {}, for labels: '{}'" , c , labels ) ; getDockerCli ( ) . removeContainerCmd ( c . getId ( ) ) . withForce ( true ) . exec ( ) ; break ; } } } catch ( NotFoundException ex ) { LOG . debug ( "Container wasn't found, that's ok" ) ; } LOG . debug ( "Recreating data container without data-image doesn't make sense, so reuse boolean." ) ; String dataContainerId = getDataContainerId ( forceRefresh ) ; final String id = getDockerCli ( ) . createContainerCmd ( JENKINS_DEFAULT . getDockerImageName ( ) ) . withEnv ( CONTAINER_JAVA_OPTS ) . withExposedPorts ( new ExposedPort ( JENKINS_DEFAULT . tcpPort ) ) . withPortSpecs ( String . format ( "%d/tcp" , JENKINS_DEFAULT . tcpPort ) ) . withHostConfig ( HostConfig . newHostConfig ( ) . withPortBindings ( PortBinding . parse ( "0.0.0.0:48000:48000" ) ) . withVolumesFrom ( new VolumesFrom ( dataContainerId ) ) . withPublishAllPorts ( true ) ) . withLabels ( labels ) // .withPortBindings(PortBinding.parse("0.0.0.0:48000:48000"), PortBinding.parse("0.0.0.0:50000:50000")) . exec ( ) . getId ( ) ; provisioned . add ( id ) ; LOG . debug ( "Starting container" ) ; getDockerCli ( ) . startContainerCmd ( id ) . exec ( ) ; return id ; } | Run record and remove after test container with jenkins . | 601 | 12 |
12,273 | public String generateDockerfileFor ( Map < String , File > plugins ) throws IOException { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "FROM scratch" ) . append ( NL ) . append ( "MAINTAINER Kanstantsin Shautsou <kanstantsin.sha@gmail.com>" ) . append ( NL ) . append ( "COPY ./ /" ) . append ( NL ) . append ( "VOLUME /usr/share/jenkins/ref" ) . append ( NL ) ; for ( Map . Entry < String , String > entry : generateLabels ( plugins ) . entrySet ( ) ) { builder . append ( "LABEL " ) . append ( entry . getKey ( ) ) . append ( "=" ) . append ( entry . getValue ( ) ) . append ( NL ) ; } // newClientBuilderForConnector.append("LABEL GENERATION_UUID=").append(UUID.randomUUID()).append(NL); return builder . toString ( ) ; } | Dockerfile as String based on sratch for placing plugins . | 226 | 13 |
12,274 | private DockerCLI createCliWithWait ( URL url , int port ) throws InterruptedException , IOException { DockerCLI tempCli = null ; boolean connected = false ; int i = 0 ; while ( i <= 10 && ! connected ) { i ++ ; try { final CLIConnectionFactory factory = new CLIConnectionFactory ( ) . url ( url ) ; tempCli = new DockerCLI ( factory , port ) ; final String channelName = tempCli . getChannel ( ) . getName ( ) ; if ( channelName . contains ( "CLI connection to" ) ) { tempCli . upgrade ( ) ; connected = true ; LOG . debug ( channelName ) ; } else { LOG . debug ( "Cli connection is not via CliPort '{}'. Sleeping for 5s..." , channelName ) ; tempCli . close ( ) ; Thread . sleep ( 5 * 1000 ) ; } } catch ( IOException e ) { LOG . debug ( "Jenkins is not available. Sleeping for 5s..." , e . getMessage ( ) ) ; Thread . sleep ( 5 * 1000 ) ; } } if ( ! connected ) { throw new IOException ( "Can't connect to {}" + url . toString ( ) ) ; } LOG . info ( "Jenkins future {}" , url ) ; LOG . info ( "Jenkins future {}/configure" , url ) ; LOG . info ( "Jenkins future {}/log/all" , url ) ; return tempCli ; } | Create DockerCLI connection against specified jnlpSlaveAgent port | 327 | 14 |
12,275 | @ Override @ GuardedBy ( "hudson.model.Queue.lock" ) public long check ( final AbstractCloudComputer c ) { final AbstractCloudSlave computerNode = c . getNode ( ) ; if ( c . isIdle ( ) && computerNode != null ) { final long idleMilliseconds = System . currentTimeMillis ( ) - c . getIdleStartMilliseconds ( ) ; if ( idleMilliseconds > MINUTES . toMillis ( idleMinutes ) ) { LOG . info ( "Disconnecting {}, after {} min timeout." , c . getName ( ) , idleMinutes ) ; try { computerNode . terminate ( ) ; } catch ( InterruptedException | IOException e ) { LOG . warn ( "Failed to terminate {}" , c . getName ( ) , e ) ; } } } return 1 ; } | While x - stream serialisation buggy copy implementation . | 189 | 10 |
12,276 | public static boolean isSomethingHappening ( Jenkins jenkins ) { if ( ! jenkins . getQueue ( ) . isEmpty ( ) ) return true ; for ( Computer n : jenkins . getComputers ( ) ) if ( ! n . isIdle ( ) ) return true ; return false ; } | Returns true if Hudson is building something or going to build something . | 68 | 13 |
12,277 | public static void waitUntilNoActivityUpTo ( Jenkins jenkins , int timeout ) throws Exception { long startTime = System . currentTimeMillis ( ) ; int streak = 0 ; while ( true ) { Thread . sleep ( 10 ) ; if ( isSomethingHappening ( jenkins ) ) { streak = 0 ; } else { streak ++ ; } if ( streak > 5 ) { // the system is quiet for a while return ; } if ( System . currentTimeMillis ( ) - startTime > timeout ) { List < Queue . Executable > building = new ArrayList < Queue . Executable > ( ) ; for ( Computer c : jenkins . getComputers ( ) ) { for ( Executor e : c . getExecutors ( ) ) { if ( e . isBusy ( ) ) building . add ( e . getCurrentExecutable ( ) ) ; } for ( Executor e : c . getOneOffExecutors ( ) ) { if ( e . isBusy ( ) ) building . add ( e . getCurrentExecutable ( ) ) ; } } dumpThreads ( ) ; throw new AssertionError ( String . format ( "Jenkins is still doing something after %dms: queue=%s building=%s" , timeout , Arrays . asList ( jenkins . getQueue ( ) . getItems ( ) ) , building ) ) ; } } } | Waits until Hudson finishes building everything including those in the queue or fail the test if the specified timeout milliseconds is | 304 | 22 |
12,278 | public boolean waitUp ( String cloudId , DockerSlaveTemplate dockerSlaveTemplate , InspectContainerResponse containerInspect ) { if ( isFalse ( containerInspect . getState ( ) . getRunning ( ) ) ) { throw new IllegalStateException ( "Container '" + containerInspect . getId ( ) + "' is not running!" ) ; } return true ; } | Wait until slave is up and ready for connection . | 79 | 10 |
12,279 | public ClientBuilderForConnector forConnector ( DockerConnector connector ) throws UnrecoverableKeyException , NoSuchAlgorithmException , KeyStoreException , KeyManagementException { LOG . debug ( "Building connection to docker host '{}'" , connector . getServerUrl ( ) ) ; withCredentialsId ( connector . getCredentialsId ( ) ) ; withConnectorType ( connector . getConnectorType ( ) ) ; withConnectTimeout ( connector . getConnectTimeout ( ) ) ; withReadTimeout ( connector . getReadTimeout ( ) ) ; return forServer ( connector . getServerUrl ( ) , connector . getApiVersion ( ) ) ; } | Provides ready to use docker client with information from docker connector | 137 | 12 |
12,280 | public ClientBuilderForConnector withCredentialsId ( String credentialsId ) throws UnrecoverableKeyException , NoSuchAlgorithmException , KeyStoreException , KeyManagementException { if ( isNotBlank ( credentialsId ) ) { withCredentials ( lookupSystemCredentials ( credentialsId ) ) ; } else { withSslConfig ( null ) ; } return this ; } | Sets SSLConfig from defined credentials id . | 81 | 9 |
12,281 | public static Credentials lookupSystemCredentials ( String credentialsId ) { return firstOrNull ( lookupCredentials ( Credentials . class , Jenkins . getInstance ( ) , ACL . SYSTEM , emptyList ( ) ) , withId ( credentialsId ) ) ; } | Util method to find credential by id in jenkins | 58 | 12 |
12,282 | @ Nonnull public List < DockerSlaveTemplate > getTemplates ( Label label ) { List < DockerSlaveTemplate > dockerSlaveTemplates = new ArrayList <> ( ) ; for ( DockerSlaveTemplate t : templates ) { if ( isNull ( label ) && t . getMode ( ) == Node . Mode . NORMAL ) { dockerSlaveTemplates . add ( t ) ; } if ( nonNull ( label ) && label . matches ( t . getLabelSet ( ) ) ) { dockerSlaveTemplates . add ( t ) ; } } return dockerSlaveTemplates ; } | Multiple templates may have the same label . | 129 | 8 |
12,283 | public void setTemplates ( List < DockerSlaveTemplate > replaceTemplates ) { if ( replaceTemplates != null ) { templates = new ArrayList <> ( replaceTemplates ) ; } else { templates = Collections . emptyList ( ) ; } } | Set list of available templates | 54 | 5 |
12,284 | protected void decrementAmiSlaveProvision ( DockerSlaveTemplate container ) { synchronized ( provisionedImages ) { int currentProvisioning = 0 ; if ( provisionedImages . containsKey ( container ) ) { currentProvisioning = provisionedImages . get ( container ) ; } provisionedImages . put ( container , Math . max ( currentProvisioning - 1 , 0 ) ) ; } } | Decrease the count of slaves being provisioned . | 86 | 10 |
12,285 | public void execInternal ( @ Nonnull final DockerClient client , @ Nonnull final String imageName , TaskListener listener ) throws IOException { PrintStream llog = listener . getLogger ( ) ; if ( shouldPullImage ( client , imageName ) ) { LOG . info ( "Pulling image '{}'. This may take awhile..." , imageName ) ; llog . println ( String . format ( "Pulling image '%s'. This may take awhile..." , imageName ) ) ; long startTime = System . currentTimeMillis ( ) ; final PullImageCmd pullImageCmd = client . pullImageCmd ( imageName ) ; // final AuthConfig authConfig = pullImageCmd.getAuthConfig(); for ( DockerRegistryCredential cred : getRegistriesCreds ( ) ) { // hostname requirements? Credentials credentials = lookupSystemCredentials ( cred . getCredentialsId ( ) ) ; // final String registryAddr = cred.getRegistryAddr(); if ( credentials instanceof DockerRegistryAuthCredentials ) { final DockerRegistryAuthCredentials authCredentials = ( DockerRegistryAuthCredentials ) credentials ; // TODO update docker-java for multiple entries pullImageCmd . withAuthConfig ( authCredentials . getAuthConfig ( ) ) ; } } // Deprecated if ( StringUtils . isNotBlank ( credentialsId ) ) { // hostname requirements? Credentials credentials = lookupSystemCredentials ( credentialsId ) ; if ( credentials instanceof DockerRegistryAuthCredentials ) { final DockerRegistryAuthCredentials authCredentials = ( DockerRegistryAuthCredentials ) credentials ; pullImageCmd . withAuthConfig ( authCredentials . getAuthConfig ( ) ) ; } } try { pullImageCmd . exec ( new DockerPullImageListenerLogger ( listener ) ) . awaitSuccess ( ) ; } catch ( DockerClientException exception ) { String exMsg = exception . getMessage ( ) ; if ( exMsg . contains ( "Could not pull image: Digest:" ) || exMsg . contains ( ": downloaded" ) ) { try { client . inspectImageCmd ( imageName ) . exec ( ) ; } catch ( NotFoundException notFoundEx ) { throw exception ; } } else { throw exception ; } } long pullTime = System . currentTimeMillis ( ) - startTime ; LOG . info ( "Finished pulling image '{}', took {} ms" , imageName , pullTime ) ; llog . println ( String . format ( "Finished pulling image '%s', took %d ms" , imageName , pullTime ) ) ; } } | Action around image with defined configuration | 570 | 6 |
12,286 | public void resolveCreds ( ) { final AuthConfigurations authConfigs = new AuthConfigurations ( ) ; for ( Map . Entry < String , String > entry : creds . entrySet ( ) ) { final String registry = entry . getKey ( ) ; final String credId = entry . getValue ( ) ; final Credentials credentials = ClientBuilderForConnector . lookupSystemCredentials ( credId ) ; if ( credentials instanceof UsernamePasswordCredentials ) { final UsernamePasswordCredentials upCreds = ( UsernamePasswordCredentials ) credentials ; final AuthConfig authConfig = new AuthConfig ( ) . withRegistryAddress ( registry ) . withPassword ( upCreds . getPassword ( ) ) . withUsername ( upCreds . getUserName ( ) ) ; authConfigs . addConfig ( authConfig ) ; } else if ( credentials instanceof DockerRegistryAuthCredentials ) { final DockerRegistryAuthCredentials authCredentials = ( DockerRegistryAuthCredentials ) credentials ; authConfigs . addConfig ( authCredentials . getAuthConfig ( ) . withRegistryAddress ( registry ) ) ; } } this . authConfigurations = authConfigs ; } | Fill additional object with resolved creds . For example before transfering object to remote . | 262 | 17 |
12,287 | protected List < DockerCloud > getAvailableDockerClouds ( Label label ) { return getAllDockerClouds ( ) . stream ( ) . filter ( cloud -> cloud . canProvision ( label ) && ( countCurrentDockerSlaves ( cloud ) >= 0 ) && ( countCurrentDockerSlaves ( cloud ) < cloud . getContainerCap ( ) ) ) . collect ( Collectors . toList ( ) ) ; } | Get a list of available DockerCloud clouds which are not at max capacity . | 91 | 15 |
12,288 | public static AppEngineDescriptor parse ( InputStream in ) throws IOException , SAXException { Preconditions . checkNotNull ( in , "Null input" ) ; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; documentBuilderFactory . setNamespaceAware ( true ) ; return new AppEngineDescriptor ( documentBuilderFactory . newDocumentBuilder ( ) . parse ( in ) ) ; } catch ( ParserConfigurationException exception ) { throw new SAXException ( "Cannot parse appengine-web.xml" , exception ) ; } } | Parses an appengine - web . xml file . | 125 | 12 |
12,289 | public String getRuntime ( ) throws AppEngineException { String runtime = getText ( getNode ( document , "appengine-web-app" , "runtime" ) ) ; if ( runtime == null ) { runtime = "java7" ; // the default runtime when not specified. } return runtime ; } | Returns runtime from the < ; runtime> ; element of the appengine - web . xml or the default one when it is missing . | 64 | 29 |
12,290 | @ Nullable public String getServiceId ( ) throws AppEngineException { String serviceId = getText ( getNode ( document , "appengine-web-app" , "service" ) ) ; if ( serviceId != null ) { return serviceId ; } return getText ( getNode ( document , "appengine-web-app" , "module" ) ) ; } | Returns service ID from the < ; service> ; element of the appengine - web . xml or null if it is missing . Will also look at module ID . | 80 | 35 |
12,291 | private static Map < String , String > getAttributeMap ( Node parent , String nodeName , String keyAttributeName , String valueAttributeName ) throws AppEngineException { Map < String , String > nameValueAttributeMap = new HashMap <> ( ) ; if ( parent . hasChildNodes ( ) ) { for ( int i = 0 ; i < parent . getChildNodes ( ) . getLength ( ) ; i ++ ) { Node child = parent . getChildNodes ( ) . item ( i ) ; NamedNodeMap attributeMap = child . getAttributes ( ) ; if ( nodeName . equals ( child . getNodeName ( ) ) && attributeMap != null ) { Node keyNode = attributeMap . getNamedItem ( keyAttributeName ) ; if ( keyNode != null ) { Node valueNode = attributeMap . getNamedItem ( valueAttributeName ) ; try { nameValueAttributeMap . put ( keyNode . getTextContent ( ) , valueNode . getTextContent ( ) ) ; } catch ( DOMException ex ) { throw new AppEngineException ( "Failed to parse value from attribute node " + keyNode . getNodeName ( ) , ex ) ; } } } } } return nameValueAttributeMap ; } | Returns a map formed from the attributes of the nodes contained within the parent node . | 263 | 16 |
12,292 | @ Nullable private static Node getNode ( Document doc , String parentNodeName , String targetNodeName ) { NodeList parentElements = doc . getElementsByTagNameNS ( APP_ENGINE_NAMESPACE , parentNodeName ) ; if ( parentElements . getLength ( ) > 0 ) { Node parent = parentElements . item ( 0 ) ; if ( parent . hasChildNodes ( ) ) { for ( int i = 0 ; i < parent . getChildNodes ( ) . getLength ( ) ; i ++ ) { Node child = parent . getChildNodes ( ) . item ( i ) ; if ( child . getNodeName ( ) . equals ( targetNodeName ) ) { return child ; } } } } return null ; } | Returns the first node found matching the given name contained within the parent node . | 165 | 15 |
12,293 | public void login ( ) throws AppEngineException { try { runner . run ( ImmutableList . of ( "auth" , "login" ) , null ) ; } catch ( ProcessHandlerException | IOException ex ) { throw new AppEngineException ( ex ) ; } } | Launches the gcloud auth login flow . | 57 | 9 |
12,294 | public void activateServiceAccount ( Path jsonFile ) throws AppEngineException { Preconditions . checkArgument ( Files . exists ( jsonFile ) , "File does not exist: " + jsonFile ) ; try { List < String > args = new ArrayList <> ( 3 ) ; args . add ( "auth" ) ; args . add ( "activate-service-account" ) ; args . addAll ( GcloudArgs . get ( "key-file" , jsonFile ) ) ; runner . run ( args , null ) ; } catch ( ProcessHandlerException | IOException ex ) { throw new AppEngineException ( ex ) ; } } | Activates a service account based on a configured json key file . | 136 | 13 |
12,295 | @ Override public int compareTo ( CloudSdkVersion other ) { Preconditions . checkNotNull ( other ) ; if ( "HEAD" . equals ( version ) && ! "HEAD" . equals ( other . version ) ) { return 1 ; } else if ( ! "HEAD" . equals ( version ) && "HEAD" . equals ( other . version ) ) { return - 1 ; } // First, compare required fields List < Integer > mine = ImmutableList . of ( majorVersion , minorVersion , patchVersion ) ; List < Integer > others = ImmutableList . of ( other . majorVersion , other . minorVersion , other . patchVersion ) ; for ( int i = 0 ; i < mine . size ( ) ; i ++ ) { int result = mine . get ( i ) . compareTo ( others . get ( i ) ) ; if ( result != 0 ) { return result ; } } // Compare pre-release components if ( preRelease != null && other . getPreRelease ( ) != null ) { return preRelease . compareTo ( other . getPreRelease ( ) ) ; } // A SemVer with a pre-release string has lower precedence than one without. if ( preRelease == null && other . getPreRelease ( ) != null ) { return 1 ; } if ( preRelease != null && other . getPreRelease ( ) == null ) { return - 1 ; } return 0 ; } | Compares this to another CloudSdkVersion per the Semantic Versioning 2 . 0 . 0 specification . | 299 | 22 |
12,296 | public void deploy ( DeployConfiguration config ) throws AppEngineException { Preconditions . checkNotNull ( config ) ; Preconditions . checkNotNull ( config . getDeployables ( ) ) ; Preconditions . checkArgument ( config . getDeployables ( ) . size ( ) > 0 ) ; Path workingDirectory = null ; List < String > arguments = new ArrayList <> ( ) ; arguments . add ( "app" ) ; arguments . add ( "deploy" ) ; // Unfortunately, 'gcloud app deploy' does not let you pass a staging directory as a deployable. // Instead, we have to run 'gcloud app deploy' from the staging directory to achieve this. // So, if we find that the only deployable in the list is a directory, we just run the command // from that directory without passing in any deployables to gcloud. if ( config . getDeployables ( ) . size ( ) == 1 && Files . isDirectory ( config . getDeployables ( ) . get ( 0 ) ) ) { workingDirectory = config . getDeployables ( ) . get ( 0 ) ; } else { for ( Path deployable : config . getDeployables ( ) ) { if ( ! Files . exists ( deployable ) ) { throw new IllegalArgumentException ( "Deployable " + deployable + " does not exist." ) ; } arguments . add ( deployable . toString ( ) ) ; } } arguments . addAll ( GcloudArgs . get ( "bucket" , config . getBucket ( ) ) ) ; arguments . addAll ( GcloudArgs . get ( "image-url" , config . getImageUrl ( ) ) ) ; arguments . addAll ( GcloudArgs . get ( "promote" , config . getPromote ( ) ) ) ; arguments . addAll ( GcloudArgs . get ( "server" , config . getServer ( ) ) ) ; arguments . addAll ( GcloudArgs . get ( "stop-previous-version" , config . getStopPreviousVersion ( ) ) ) ; arguments . addAll ( GcloudArgs . get ( "version" , config . getVersion ( ) ) ) ; arguments . addAll ( GcloudArgs . get ( "project" , config . getProjectId ( ) ) ) ; try { runner . run ( arguments , workingDirectory ) ; } catch ( ProcessHandlerException | IOException ex ) { throw new AppEngineException ( ex ) ; } } | Deploys a project to App Engine . | 521 | 8 |
12,297 | @ Override public int compareTo ( CloudSdkVersionPreRelease other ) { Preconditions . checkNotNull ( other ) ; // Compare segments from left to right. A smaller number of pre-release segments comes before a // higher number, if all preceding segments are equal. int index = 0 ; while ( index < this . segments . size ( ) && index < other . segments . size ( ) ) { int result = this . segments . get ( index ) . compareTo ( other . segments . get ( index ) ) ; if ( result != 0 ) { return result ; } index ++ ; } // If we've reached this point, the smaller list comes first. if ( this . segments . size ( ) < other . segments . size ( ) ) { return - 1 ; } else if ( this . segments . size ( ) > other . segments . size ( ) ) { return 1 ; } return 0 ; } | Compares this to another CloudSdkVersionPreRelease . | 192 | 12 |
12,298 | public static boolean contains ( String className ) { if ( className . startsWith ( "javax." ) ) { return ! isBundledInJre ( className ) || WHITELIST . contains ( className ) ; } else if ( className . startsWith ( "java." ) || className . startsWith ( "sun.util." ) || className . startsWith ( "org.xml.sax." ) || className . startsWith ( "org.w3c.dom." ) || className . startsWith ( "org.omg." ) || className . startsWith ( "org.ietf.jgss." ) // com.sun and com.oracle packages are tricky. Some are in the JRE. Some aren't. || className . startsWith ( "com.sun.jmx." ) || className . startsWith ( "com.sun.jndi." ) || className . startsWith ( "com.sun.media." ) || className . startsWith ( "com.sun.management." ) || className . startsWith ( "com.sun.beans." ) || className . startsWith ( "com.sun.corba." ) || className . startsWith ( "com.sun.awt." ) || className . startsWith ( "com.sun.swing." ) || className . startsWith ( "com.sun.rmi." ) || className . startsWith ( "com.sun.xml." ) || className . startsWith ( "com.sun.java." ) || className . startsWith ( "com.sun.org." ) || className . startsWith ( "com.sun.rowset." ) || className . startsWith ( "com.oracle.net." ) || className . startsWith ( "com.oracle.nio." ) || className . startsWith ( "com.oracle.util." ) ) { return WHITELIST . contains ( className ) ; } else { // not a JRE class return true ; } } | Determine whether class is allowed in App Engine Standard . | 446 | 12 |
12,299 | private static boolean isBundledInJre ( String className ) { if ( className . startsWith ( "javax.accessibility." ) || className . startsWith ( "javax.activation." ) || className . startsWith ( "javax.activity." ) || className . startsWith ( "javax.annotation." ) || className . startsWith ( "javax.crypto." ) || className . startsWith ( "javax.imageio." ) || className . startsWith ( "javax.jws." ) || className . startsWith ( "javax.lang.model." ) || className . startsWith ( "javax.management." ) || className . startsWith ( "javax.naming." ) || className . startsWith ( "javax.net." ) || className . startsWith ( "javax.print." ) || className . startsWith ( "javax.rmi." ) || className . startsWith ( "javax.script." ) || className . startsWith ( "javax.security." ) || className . startsWith ( "javax.sound." ) || className . startsWith ( "javax.sql." ) || className . startsWith ( "javax.swing." ) || className . startsWith ( "javax.tools." ) || className . startsWith ( "javax.transaction." ) || className . startsWith ( "javax.xml." ) ) { return true ; } return false ; } | javax packages are tricky . Some are in the JRE . Some aren t . | 352 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.