idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
7,100
public final boolean hasProperty ( final String property ) { final String val = properties . get ( property ) ; if ( val == null ) return false ; if ( val . isEmpty ( ) ) return false ; return true ; }
Determines if the given propery is in the map
7,101
public final String dumpConfiguration ( ) { if ( properties . isEmpty ( ) ) return "No configuration settings stored" ; StringBuilder response = new StringBuilder ( "TSD Configuration:\n" ) ; response . append ( "File [" + config_location + "]\n" ) ; int line = 0 ; for ( Map . Entry < String , String > entry : properties . entrySet ( ) ) { if ( line > 0 ) { response . append ( "\n" ) ; } response . append ( "Key [" + entry . getKey ( ) + "] Value [" ) ; if ( entry . getKey ( ) . toUpperCase ( ) . contains ( "PASS" ) ) { response . append ( "********" ) ; } else { response . append ( entry . getValue ( ) ) ; } response . append ( "]" ) ; line ++ ; } return response . toString ( ) ; }
Returns a simple string with the configured properties for debugging
7,102
protected void loadConfig ( ) throws IOException { if ( config_location != null && ! config_location . isEmpty ( ) ) { loadConfig ( config_location ) ; return ; } final ArrayList < String > file_locations = new ArrayList < String > ( ) ; file_locations . add ( "opentsdb.conf" ) ; if ( System . getProperty ( "os.name" ) . toUpperCase ( ) . contains ( "WINDOWS" ) ) { file_locations . add ( "C:\\Program Files\\opentsdb\\opentsdb.conf" ) ; file_locations . add ( "C:\\Program Files (x86)\\opentsdb\\opentsdb.conf" ) ; } else { file_locations . add ( "/etc/opentsdb.conf" ) ; file_locations . add ( "/etc/opentsdb/opentsdb.conf" ) ; file_locations . add ( "/opt/opentsdb/opentsdb.conf" ) ; } for ( String file : file_locations ) { try { FileInputStream file_stream = new FileInputStream ( file ) ; Properties props = new Properties ( ) ; props . load ( file_stream ) ; loadHashMap ( props ) ; } catch ( Exception e ) { LOG . debug ( "Unable to find or load " + file , e ) ; continue ; } LOG . info ( "Successfully loaded configuration file: " + file ) ; config_location = file ; return ; } LOG . info ( "No configuration found, will use defaults" ) ; }
Searches a list of locations for a valid opentsdb . conf file
7,103
protected void loadConfig ( final String file ) throws FileNotFoundException , IOException { final FileInputStream file_stream = new FileInputStream ( file ) ; try { final Properties props = new Properties ( ) ; props . load ( file_stream ) ; loadHashMap ( props ) ; LOG . info ( "Successfully loaded configuration file: " + file ) ; config_location = file ; } finally { file_stream . close ( ) ; } }
Attempts to load the configuration from the given location
7,104
public void loadStaticVariables ( ) { auto_metric = this . getBoolean ( "tsd.core.auto_create_metrics" ) ; auto_tagk = this . getBoolean ( "tsd.core.auto_create_tagks" ) ; auto_tagv = this . getBoolean ( "tsd.core.auto_create_tagvs" ) ; enable_compactions = this . getBoolean ( "tsd.storage.enable_compaction" ) ; enable_appends = this . getBoolean ( "tsd.storage.enable_appends" ) ; repair_appends = this . getBoolean ( "tsd.storage.repair_appends" ) ; enable_chunked_requests = this . getBoolean ( "tsd.http.request.enable_chunked" ) ; enable_realtime_ts = this . getBoolean ( "tsd.core.meta.enable_realtime_ts" ) ; enable_realtime_uid = this . getBoolean ( "tsd.core.meta.enable_realtime_uid" ) ; enable_tsuid_incrementing = this . getBoolean ( "tsd.core.meta.enable_tsuid_incrementing" ) ; enable_tsuid_tracking = this . getBoolean ( "tsd.core.meta.enable_tsuid_tracking" ) ; if ( this . hasProperty ( "tsd.http.request.max_chunk" ) ) { max_chunked_requests = this . getInt ( "tsd.http.request.max_chunk" ) ; } if ( this . hasProperty ( "tsd.http.header_tag" ) ) { http_header_tag = this . getString ( "tsd.http.header_tag" ) ; } enable_tree_processing = this . getBoolean ( "tsd.core.tree.enable_processing" ) ; fix_duplicates = this . getBoolean ( "tsd.storage.fix_duplicates" ) ; scanner_max_num_rows = this . getInt ( "tsd.storage.hbase.scanner.maxNumRows" ) ; use_otsdb_timestamp = this . getBoolean ( "tsd.storage.use_otsdb_timestamp" ) ; get_date_tiered_compaction_start = this . getLong ( "tsd.storage.get_date_tiered_compaction_start" ) ; use_max_value = this . getBoolean ( "tsd.storage.use_max_value" ) ; }
Loads the static class variables for values that are called often . This should be called any time the configuration changes .
7,105
public void add ( final String name , final String value ) { ArrayList < String > values = super . get ( name ) ; if ( values == null ) { values = new ArrayList < String > ( 1 ) ; super . put ( name , values ) ; } values . add ( value ) ; }
Adds a query string element .
7,106
public ChannelBuffer formatPutV1 ( final Map < String , Object > results ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatPutV1" ) ; }
Formats the results of an HTTP data point storage request
7,107
public ChannelBuffer formatSuggestV1 ( final List < String > suggestions ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatSuggestV1" ) ; }
Formats a suggestion response
7,108
public ChannelBuffer formatAggregatorsV1 ( final Set < String > aggregators ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatAggregatorsV1" ) ; }
Format the list of implemented aggregators
7,109
public ChannelBuffer formatVersionV1 ( final Map < String , String > version ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatVersionV1" ) ; }
Format a hash map of information about the OpenTSDB version
7,110
public ChannelBuffer formatDropCachesV1 ( final Map < String , String > response ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatDropCachesV1" ) ; }
Format a response from the DropCaches call
7,111
public ChannelBuffer formatLastPointQueryV1 ( final List < IncomingDataPoint > data_points ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatLastPointQueryV1" ) ; }
Format a list of last data points
7,112
public ChannelBuffer formatTSMetaListV1 ( final List < TSMeta > metas ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatTSMetaV1" ) ; }
Format a a list of TSMeta objects
7,113
public ChannelBuffer formatTreesV1 ( final List < Tree > trees ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatTreesV1" ) ; }
Format a list of tree objects . Note that the list may be empty if no trees were present .
7,114
public ChannelBuffer formatTreeCollisionNotMatchedV1 ( final Map < String , String > results , final boolean is_collisions ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatTreeCollisionNotMatched" ) ; }
Format a map of one or more TSUIDs that collided or were not matched
7,115
public ChannelBuffer formatAnnotationsV1 ( final List < Annotation > notes ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatAnnotationsV1" ) ; }
Format a list of annotation objects
7,116
public ChannelBuffer formatStatsV1 ( final List < IncomingDataPoint > stats ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatStatsV1" ) ; }
Format a list of statistics
7,117
public ChannelBuffer formatThreadStatsV1 ( final List < Map < String , Object > > stats ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatThreadStatsV1" ) ; }
Format a list of thread statistics
7,118
public ChannelBuffer formatQueryStatsV1 ( final Map < String , Object > query_stats ) { throw new BadRequestException ( HttpResponseStatus . NOT_IMPLEMENTED , "The requested API endpoint has not been implemented" , this . getClass ( ) . getCanonicalName ( ) + " has not implemented formatQueryStatsV1" ) ; }
Format the query stats
7,119
public static final String getDurationUnits ( final String duration ) { if ( duration == null || duration . isEmpty ( ) ) { throw new IllegalArgumentException ( "Duration cannot be null or empty" ) ; } int unit = 0 ; while ( unit < duration . length ( ) && Character . isDigit ( duration . charAt ( unit ) ) ) { unit ++ ; } final String units = duration . substring ( unit ) . toLowerCase ( ) ; if ( units . equals ( "ms" ) || units . equals ( "s" ) || units . equals ( "m" ) || units . equals ( "h" ) || units . equals ( "d" ) || units . equals ( "w" ) || units . equals ( "n" ) || units . equals ( "y" ) ) { return units ; } throw new IllegalArgumentException ( "Invalid units in the duration: " + units ) ; }
Returns the suffix or units of the duration as a string . The result will be ms s m h d w n or y .
7,120
public static final int getDurationInterval ( final String duration ) { if ( duration == null || duration . isEmpty ( ) ) { throw new IllegalArgumentException ( "Duration cannot be null or empty" ) ; } if ( duration . contains ( "." ) ) { throw new IllegalArgumentException ( "Floating point intervals are not supported" ) ; } int unit = 0 ; while ( Character . isDigit ( duration . charAt ( unit ) ) ) { unit ++ ; } int interval ; try { interval = Integer . parseInt ( duration . substring ( 0 , unit ) ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Invalid duration (number): " + duration ) ; } if ( interval <= 0 ) { throw new IllegalArgumentException ( "Zero or negative duration: " + duration ) ; } return interval ; }
Parses the prefix of the duration the interval and returns it as a number . E . g . if you supply 1d it will return 1 . If you supply 60m it will return 60 .
7,121
public static void setTimeZone ( final SimpleDateFormat fmt , final String tzname ) { if ( tzname == null ) { return ; } final TimeZone tz = DateTime . timezones . get ( tzname ) ; if ( tz != null ) { fmt . setTimeZone ( tz ) ; } else { throw new IllegalArgumentException ( "Invalid timezone name: " + tzname ) ; } }
Applies the given timezone to the given date format .
7,122
public static double msFromNanoDiff ( final long end , final long start ) { if ( end < start ) { throw new IllegalArgumentException ( "End (" + end + ") cannot be less " + "than start (" + start + ")" ) ; } return ( ( double ) end - ( double ) start ) / 1000000 ; }
Calculates the difference between two values and returns the time in milliseconds as a double .
7,123
public static int unitsToCalendarType ( final String units ) { if ( units == null || units . isEmpty ( ) ) { throw new IllegalArgumentException ( "Units cannot be null or empty" ) ; } final String lc = units . toLowerCase ( ) ; if ( lc . equals ( "ms" ) ) { return Calendar . MILLISECOND ; } else if ( lc . equals ( "s" ) ) { return Calendar . SECOND ; } else if ( lc . equals ( "m" ) ) { return Calendar . MINUTE ; } else if ( lc . equals ( "h" ) ) { return Calendar . HOUR_OF_DAY ; } else if ( lc . equals ( "d" ) ) { return Calendar . DAY_OF_MONTH ; } else if ( lc . equals ( "w" ) ) { return Calendar . DAY_OF_WEEK ; } else if ( lc . equals ( "n" ) ) { return Calendar . MONTH ; } else if ( lc . equals ( "y" ) ) { return Calendar . YEAR ; } throw new IllegalArgumentException ( "Unrecognized unit type: " + units ) ; }
Return the proper Calendar time unit as an integer given the string
7,124
public void validate ( ) { if ( id == null || id . isEmpty ( ) ) { throw new IllegalArgumentException ( "missing or empty id" ) ; } Query . validateId ( id ) ; }
Validates the output
7,125
public static Aggregator get ( final String name ) { final Aggregator agg = aggregators . get ( name ) ; if ( agg != null ) { return agg ; } throw new NoSuchElementException ( "No such aggregator: " + name ) ; }
Returns the aggregator corresponding to the given name .
7,126
public Deferred < Object > delete ( final TSDB tsdb ) { if ( start_time < 1 ) { throw new IllegalArgumentException ( "The start timestamp has not been set" ) ; } final byte [ ] tsuid_byte = tsuid != null && ! tsuid . isEmpty ( ) ? UniqueId . stringToUid ( tsuid ) : null ; final DeleteRequest delete = new DeleteRequest ( tsdb . dataTable ( ) , getRowKey ( start_time , tsuid_byte ) , FAMILY , getQualifier ( start_time ) ) ; return tsdb . getClient ( ) . delete ( delete ) ; }
Attempts to mark an Annotation object for deletion . Note that if the annoation does not exist in storage this delete call will not throw an error .
7,127
public static Deferred < Annotation > getAnnotation ( final TSDB tsdb , final long start_time ) { return getAnnotation ( tsdb , ( byte [ ] ) null , start_time ) ; }
Attempts to fetch a global annotation from storage
7,128
public static Deferred < List < Annotation > > getGlobalAnnotations ( final TSDB tsdb , final long start_time , final long end_time ) { if ( end_time < 1 ) { throw new IllegalArgumentException ( "The end timestamp has not been set" ) ; } if ( end_time < start_time ) { throw new IllegalArgumentException ( "The end timestamp cannot be less than the start timestamp" ) ; } final class ScannerCB implements Callback < Deferred < List < Annotation > > , ArrayList < ArrayList < KeyValue > > > { final Scanner scanner ; final ArrayList < Annotation > annotations = new ArrayList < Annotation > ( ) ; public ScannerCB ( ) { final byte [ ] start = new byte [ Const . SALT_WIDTH ( ) + TSDB . metrics_width ( ) + Const . TIMESTAMP_BYTES ] ; final byte [ ] end = new byte [ Const . SALT_WIDTH ( ) + TSDB . metrics_width ( ) + Const . TIMESTAMP_BYTES ] ; final long normalized_start = ( start_time - ( start_time % Const . MAX_TIMESPAN ) ) ; final long normalized_end = ( end_time - ( end_time % Const . MAX_TIMESPAN ) + Const . MAX_TIMESPAN ) ; Bytes . setInt ( start , ( int ) normalized_start , Const . SALT_WIDTH ( ) + TSDB . metrics_width ( ) ) ; Bytes . setInt ( end , ( int ) normalized_end , Const . SALT_WIDTH ( ) + TSDB . metrics_width ( ) ) ; scanner = tsdb . getClient ( ) . newScanner ( tsdb . dataTable ( ) ) ; scanner . setStartKey ( start ) ; scanner . setStopKey ( end ) ; scanner . setFamily ( FAMILY ) ; } public Deferred < List < Annotation > > scan ( ) { return scanner . nextRows ( ) . addCallbackDeferring ( this ) ; } public Deferred < List < Annotation > > call ( final ArrayList < ArrayList < KeyValue > > rows ) throws Exception { if ( rows == null || rows . isEmpty ( ) ) { return Deferred . fromResult ( ( List < Annotation > ) annotations ) ; } for ( final ArrayList < KeyValue > row : rows ) { for ( KeyValue column : row ) { if ( ( column . qualifier ( ) . length == 3 || column . qualifier ( ) . length == 5 ) && column . qualifier ( ) [ 0 ] == PREFIX ( ) ) { Annotation note = JSON . parseToObject ( column . value ( ) , Annotation . class ) ; if ( note . start_time < start_time || note . end_time > end_time ) { continue ; } annotations . add ( note ) ; } } } return scan ( ) ; } } return new ScannerCB ( ) . scan ( ) ; }
Scans through the global annotation storage rows and returns a list of parsed annotation objects . If no annotations were found for the given timespan the resulting list will be empty .
7,129
private static long timeFromQualifier ( final byte [ ] qualifier , final long base_time ) { final long offset ; if ( qualifier . length == 3 ) { offset = Bytes . getUnsignedShort ( qualifier , 1 ) ; return ( base_time + offset ) * 1000 ; } else { offset = Bytes . getUnsignedInt ( qualifier , 1 ) ; return ( base_time * 1000 ) + offset ; } }
Returns a timestamp after parsing an annotation qualifier .
7,130
static void checkMetricAndTags ( final String metric , final Map < String , String > tags ) { if ( tags . size ( ) <= 0 ) { throw new IllegalArgumentException ( "Need at least one tag (metric=" + metric + ", tags=" + tags + ')' ) ; } else if ( tags . size ( ) > Const . MAX_NUM_TAGS ( ) ) { throw new IllegalArgumentException ( "Too many tags: " + tags . size ( ) + " maximum allowed: " + Const . MAX_NUM_TAGS ( ) + ", tags: " + tags ) ; } Tags . validateString ( "metric name" , metric ) ; for ( final Map . Entry < String , String > tag : tags . entrySet ( ) ) { Tags . validateString ( "tag name with value [" + tag . getValue ( ) + "]" , tag . getKey ( ) ) ; Tags . validateString ( "tag value with key [" + tag . getKey ( ) + "]" , tag . getValue ( ) ) ; } }
Validates the given metric and tags .
7,131
private static void copyInRowKey ( final byte [ ] row , final short offset , final byte [ ] bytes ) { System . arraycopy ( bytes , 0 , row , offset , bytes . length ) ; }
Copies the specified byte array at the specified offset in the row key .
7,132
private long updateBaseTime ( final long timestamp ) { final long base_time = timestamp - ( timestamp % Const . MAX_TIMESPAN ) ; row = Arrays . copyOf ( row , row . length ) ; Bytes . setInt ( row , ( int ) base_time , Const . SALT_WIDTH ( ) + tsdb . metrics . width ( ) ) ; RowKey . prefixKeyWithSalt ( row ) ; tsdb . scheduleForCompaction ( row , ( int ) base_time ) ; return base_time ; }
Updates the base time in the row key .
7,133
public static void addTSDBFunctions ( final TSDB tsdb ) { available_functions . put ( "divideSeries" , new DivideSeries ( tsdb ) ) ; available_functions . put ( "divide" , new DivideSeries ( tsdb ) ) ; available_functions . put ( "sumSeries" , new SumSeries ( tsdb ) ) ; available_functions . put ( "sum" , new SumSeries ( tsdb ) ) ; available_functions . put ( "diffSeries" , new DiffSeries ( tsdb ) ) ; available_functions . put ( "difference" , new DiffSeries ( tsdb ) ) ; available_functions . put ( "multiplySeries" , new MultiplySeries ( tsdb ) ) ; available_functions . put ( "multiply" , new MultiplySeries ( tsdb ) ) ; }
Adds more functions to the map that depend on an instantiated TSDB object . Only call this once please .
7,134
public static Expression getByName ( final String function ) { final Expression expression = available_functions . get ( function ) ; if ( expression == null ) { throw new UnsupportedOperationException ( "Function " + function + " has not been implemented" ) ; } return expression ; }
Returns the expression function given the name
7,135
public void setRow ( final KeyValue column ) { if ( key != null ) { throw new IllegalStateException ( "setRow was already called on " + this ) ; } key = column . key ( ) ; if ( need_count ) { System . out . println ( "AGG ID: " + agg_id + " COUNT ID: " + count_id + " MASK: " + ( column . qualifier ( ) [ 0 ] & RollupUtils . AGGREGATOR_MASK ) ) ; if ( ( column . qualifier ( ) [ 0 ] & RollupUtils . AGGREGATOR_MASK ) == agg_id ) { append ( column , false , false ) ; } else if ( ( column . qualifier ( ) [ 0 ] & RollupUtils . AGGREGATOR_MASK ) == count_id ) { append ( column , true , false ) ; } else if ( Bytes . memcmp ( RollupQuery . SUM , column . qualifier ( ) , 0 , RollupQuery . SUM . length ) == 0 ) { append ( column , false , true ) ; } else if ( Bytes . memcmp ( RollupQuery . COUNT , column . qualifier ( ) , 0 , RollupQuery . COUNT . length ) == 0 ) { append ( column , true , true ) ; } else { throw new IllegalDataException ( "Attempt to add a different aggrregate cell =" + column + ", expected aggregator either SUM or COUNT" ) ; } } else { if ( ( column . qualifier ( ) [ 0 ] & RollupUtils . AGGREGATOR_MASK ) == agg_id ) { append ( column , false , false ) ; } else if ( Bytes . memcmp ( column . qualifier ( ) , rollup_query . getRollupAggPrefix ( ) , 0 , rollup_query . getRollupAggPrefix ( ) . length ) == 0 ) { append ( column , false , true ) ; } else { throw new IllegalDataException ( "Attempt to add a different aggrregate cell =" + column + ", expected aggregator " + Bytes . pretty ( rollup_query . getRollupAggPrefix ( ) ) ) ; } } }
Sets the row this instance holds in RAM using a row from a scanner .
7,136
public static void main ( String [ ] args ) throws Exception { ArgP argp = new ArgP ( ) ; CliOptions . addCommon ( argp ) ; argp . addOption ( "--use-data-table" , "Scan against the raw data table instead of the meta data table." ) ; args = CliOptions . parse ( argp , args ) ; if ( args == null ) { usage ( argp , "Invalid usage" ) ; System . exit ( 2 ) ; } else if ( args . length < 1 ) { usage ( argp , "Not enough arguments" ) ; System . exit ( 2 ) ; } final boolean use_data_table = argp . has ( "--use-data-table" ) ; Config config = CliOptions . getConfig ( argp ) ; final TSDB tsdb = new TSDB ( config ) ; tsdb . checkNecessaryTablesExist ( ) . joinUninterruptibly ( ) ; int rc ; try { rc = runCommand ( tsdb , use_data_table , args ) ; } finally { try { tsdb . getClient ( ) . shutdown ( ) . joinUninterruptibly ( ) ; LOG . info ( "Gracefully shutdown the TSD" ) ; } catch ( Exception e ) { LOG . error ( "Unexpected exception while shutting down" , e ) ; rc = 42 ; } } System . exit ( rc ) ; }
Entry point to run the search utility
7,137
private static int runCommand ( final TSDB tsdb , final boolean use_data_table , final String [ ] args ) throws Exception { final int nargs = args . length ; if ( args [ 0 ] . equals ( "lookup" ) ) { if ( nargs < 2 ) { usage ( null , "Not enough arguments" ) ; return 2 ; } return lookup ( tsdb , use_data_table , args ) ; } else { usage ( null , "Unknown sub command: " + args [ 0 ] ) ; return 2 ; } }
Determines the command requested of the user can calls the appropriate method .
7,138
protected Deferred < Object > importDataPoint ( final TSDB tsdb , final String [ ] words ) { words [ 0 ] = null ; if ( words . length < 5 ) { throw new IllegalArgumentException ( "not enough arguments" + " (need least 4, got " + ( words . length - 1 ) + ')' ) ; } final String metric = words [ 1 ] ; if ( metric . length ( ) <= 0 ) { throw new IllegalArgumentException ( "empty metric name" ) ; } final long timestamp ; if ( words [ 2 ] . contains ( "." ) ) { timestamp = Tags . parseLong ( words [ 2 ] . replace ( "." , "" ) ) ; } else { timestamp = Tags . parseLong ( words [ 2 ] ) ; } if ( timestamp <= 0 ) { throw new IllegalArgumentException ( "invalid timestamp: " + timestamp ) ; } final String value = words [ 3 ] ; if ( value . length ( ) <= 0 ) { throw new IllegalArgumentException ( "empty value" ) ; } final HashMap < String , String > tags = new HashMap < String , String > ( ) ; for ( int i = 4 ; i < words . length ; i ++ ) { if ( ! words [ i ] . isEmpty ( ) ) { Tags . parse ( tags , words [ i ] ) ; } } if ( Tags . looksLikeInteger ( value ) ) { return tsdb . addPoint ( metric , timestamp , Tags . parseLong ( value ) , tags ) ; } else if ( Tags . fitsInFloat ( value ) ) { return tsdb . addPoint ( metric , timestamp , Float . parseFloat ( value ) , tags ) ; } else { return tsdb . addPoint ( metric , timestamp , Double . parseDouble ( value ) , tags ) ; } }
Imports a single data point .
7,139
final private HashMap < String , Object > getHttpDetails ( final String message , final IncomingDataPoint dp ) { final HashMap < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( "error" , message ) ; map . put ( "datapoint" , dp ) ; return map ; }
Simple helper to format an error trying to save a data point
7,140
void handleStorageException ( final TSDB tsdb , final IncomingDataPoint dp , final Exception e ) { final StorageExceptionHandler handler = tsdb . getStorageExceptionHandler ( ) ; if ( handler != null ) { handler . handleError ( dp , e ) ; } }
Passes a data point off to the storage handler plugin if it has been configured .
7,141
public void addOption ( final String name , final String meta , final String help ) { if ( name . isEmpty ( ) ) { throw new IllegalArgumentException ( "empty name" ) ; } else if ( name . charAt ( 0 ) != '-' ) { throw new IllegalArgumentException ( "name must start with a `-': " + name ) ; } else if ( meta != null && meta . isEmpty ( ) ) { throw new IllegalArgumentException ( "empty meta" ) ; } else if ( help . isEmpty ( ) ) { throw new IllegalArgumentException ( "empty help" ) ; } final String [ ] prev = options . put ( name , new String [ ] { meta , help } ) ; if ( prev != null ) { options . put ( name , prev ) ; throw new IllegalArgumentException ( "Option " + name + " already defined" + " in " + this ) ; } }
Registers an option in this argument parser .
7,142
public String [ ] parse ( final String [ ] args ) { parsed = new HashMap < String , String > ( options . size ( ) ) ; ArrayList < String > unparsed = null ; for ( int i = 0 ; i < args . length ; i ++ ) { final String arg = args [ i ] ; String [ ] opt = options . get ( arg ) ; if ( opt != null ) { if ( opt [ 0 ] != null ) { if ( ++ i < args . length ) { parsed . put ( arg , args [ i ] ) ; } else { throw new IllegalArgumentException ( "Missing argument for " + arg ) ; } } else { parsed . put ( arg , null ) ; } continue ; } final int equal = arg . indexOf ( '=' , 1 ) ; if ( equal > 0 ) { final String name = arg . substring ( 0 , equal ) ; opt = options . get ( name ) ; if ( opt != null ) { parsed . put ( name , arg . substring ( equal + 1 , arg . length ( ) ) ) ; continue ; } } if ( unparsed == null ) { unparsed = new ArrayList < String > ( args . length - i ) ; } if ( ! arg . isEmpty ( ) && arg . charAt ( 0 ) == '-' ) { if ( arg . length ( ) == 2 && arg . charAt ( 1 ) == '-' ) { for ( i ++ ; i < args . length ; i ++ ) { unparsed . add ( args [ i ] ) ; } break ; } throw new IllegalArgumentException ( "Unrecognized option " + arg ) ; } unparsed . add ( arg ) ; } if ( unparsed != null ) { return unparsed . toArray ( new String [ unparsed . size ( ) ] ) ; } else { return new String [ 0 ] ; } }
Parses the command line given in argument .
7,143
public String get ( final String name , final String defaultv ) { final String value = get ( name ) ; return value == null ? defaultv : value ; }
Returns the value of the given option or a default value .
7,144
public boolean has ( final String name ) { if ( ! options . containsKey ( name ) ) { throw new IllegalArgumentException ( "Unknown option " + name ) ; } else if ( parsed == null ) { throw new IllegalStateException ( "parse() wasn't called" ) ; } return parsed . containsKey ( name ) ; }
Returns whether or not the given option was given .
7,145
public void addUsageTo ( final StringBuilder buf ) { final ArrayList < String > names = new ArrayList < String > ( options . keySet ( ) ) ; Collections . sort ( names ) ; int max_length = 0 ; for ( final String name : names ) { final String [ ] opt = options . get ( name ) ; final int length = name . length ( ) + ( opt [ 0 ] == null ? 0 : opt [ 0 ] . length ( ) + 1 ) ; if ( length > max_length ) { max_length = length ; } } for ( final String name : names ) { final String [ ] opt = options . get ( name ) ; int length = name . length ( ) ; buf . append ( " " ) . append ( name ) ; if ( opt [ 0 ] != null ) { length += opt [ 0 ] . length ( ) + 1 ; buf . append ( '=' ) . append ( opt [ 0 ] ) ; } for ( int i = length ; i <= max_length ; i ++ ) { buf . append ( ' ' ) ; } buf . append ( opt [ 1 ] ) . append ( '\n' ) ; } }
Appends the usage to the given buffer .
7,146
public String usage ( ) { final StringBuilder buf = new StringBuilder ( 16 * options . size ( ) ) ; addUsageTo ( buf ) ; return buf . toString ( ) ; }
Returns a usage string .
7,147
private static BufferedReader open ( final String path ) throws IOException { if ( path . equals ( "-" ) ) { return new BufferedReader ( new InputStreamReader ( System . in ) ) ; } InputStream is = new FileInputStream ( path ) ; if ( path . endsWith ( ".gz" ) ) { is = new GZIPInputStream ( is ) ; } return new BufferedReader ( new InputStreamReader ( is ) ) ; }
Opens a file for reading handling gzipped files .
7,148
public void validate ( ) { if ( id == null || id . isEmpty ( ) ) { throw new IllegalArgumentException ( "missing or empty id" ) ; } Query . validateId ( id ) ; if ( expr == null || expr . isEmpty ( ) ) { throw new IllegalArgumentException ( "missing or empty expr" ) ; } parsed_expression = ExpressionIterator . JEXL_ENGINE . createScript ( expr ) ; variables = new HashSet < String > ( ) ; for ( final List < String > exp_list : ExpressionIterator . JEXL_ENGINE . getVariables ( parsed_expression ) ) { for ( final String variable : exp_list ) { variables . add ( variable ) ; } } if ( join == null ) { join = Join . Builder ( ) . setOperator ( SetOperator . UNION ) . build ( ) ; } }
Validates the expression
7,149
static String [ ] parse ( final ArgP argp , String [ ] args ) { try { args = argp . parse ( args ) ; } catch ( IllegalArgumentException e ) { System . err . println ( "Invalid usage. " + e . getMessage ( ) ) ; System . exit ( 2 ) ; } honorVerboseFlag ( argp ) ; return args ; }
Parse the command line arguments with the given options .
7,150
static final Config getConfig ( final ArgP argp ) throws IOException { final Config config ; final String config_file = argp . get ( "--config" , "" ) ; if ( ! config_file . isEmpty ( ) ) config = new Config ( config_file ) ; else config = new Config ( true ) ; overloadConfig ( argp , config ) ; config . setAutoMetric ( config . getBoolean ( "tsd.core.auto_create_metrics" ) ) ; return config ; }
Attempts to load a configuration given a file or default files and overrides with command line arguments
7,151
protected static void loadConfigSource ( ConfigArgP config , String source ) { Properties p = loadConfig ( source ) ; Config c = config . getConfig ( ) ; for ( String key : p . stringPropertyNames ( ) ) { String value = p . getProperty ( key ) ; ConfigurationItem ci = config . getConfigurationItem ( key ) ; if ( ci != null ) { ci . setValue ( processConfigValue ( value ) ) ; } c . overrideConfig ( key , processConfigValue ( value ) ) ; } }
Applies the properties from the named source to the main configuration
7,152
protected static Properties loadConfig ( String name ) { try { URL url = new URL ( name ) ; return loadConfig ( url ) ; } catch ( Exception ex ) { return loadConfig ( new File ( name ) ) ; } }
Loads properties from a file or url with the passed name
7,153
protected static Properties loadConfig ( String source , InputStream is ) { try { Properties p = new Properties ( ) ; p . load ( is ) ; Set < String > keys = p . stringPropertyNames ( ) ; for ( String key : keys ) { p . setProperty ( key , p . getProperty ( key ) . trim ( ) ) ; } return p ; } catch ( IllegalArgumentException iae ) { throw iae ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Failed to load configuration from [" + source + "]" ) ; } }
Loads properties from the passed input stream
7,154
protected static Properties loadConfig ( File file ) { InputStream is = null ; try { is = new FileInputStream ( file ) ; return loadConfig ( file . getAbsolutePath ( ) , is ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Failed to load configuration from [" + file . getAbsolutePath ( ) + "]" ) ; } finally { if ( is != null ) try { is . close ( ) ; } catch ( Exception ex ) { } } }
Loads properties from the passed file
7,155
public String [ ] applyArgs ( String [ ] clargs ) { LOG . debug ( "Applying Command Line Args {}" , Arrays . toString ( clargs ) ) ; final List < String > nonFlagArgs = new ArrayList < String > ( Arrays . asList ( clargs ) ) ; extractAndApplyFlags ( nonFlagArgs ) ; String [ ] args = nonFlagArgs . toArray ( new String [ 0 ] ) ; String [ ] nonArgs = argp . parse ( args ) ; LOG . debug ( "Applying Command Line ArgP {}" , argp ) ; LOG . debug ( "configItemsByCl Keys: [{}]" , configItemsByCl . toString ( ) ) ; for ( Map . Entry < String , String > entry : argp . getParsed ( ) . entrySet ( ) ) { String key = entry . getKey ( ) , value = entry . getValue ( ) ; ConfigurationItem citem = getConfigurationItemByClOpt ( key ) ; LOG . debug ( "Loaded CI for command line option [{}]: Found:{}" , key , citem != null ) ; if ( "BOOL" . equals ( citem . getMeta ( ) ) ) { citem . setValue ( value != null ? value : "true" ) ; } else { if ( value != null ) { citem . setValue ( processConfigValue ( value ) ) ; } } config . overrideConfig ( citem . getKey ( ) , citem . getValue ( ) ) ; } return nonArgs ; }
Parses the command line arguments and where the options are recognized config items the value is validated then applied to the config
7,156
public String getDefaultUsage ( String ... msgs ) { StringBuilder b = new StringBuilder ( "\n" ) ; for ( String msg : msgs ) { b . append ( msg ) . append ( "\n" ) ; } b . append ( dargp . usage ( ) ) ; return b . toString ( ) ; }
Returns a default usage banner with optional prefixed messages one per line .
7,157
public String getExtendedUsage ( String ... msgs ) { StringBuilder b = new StringBuilder ( "\n" ) ; for ( String msg : msgs ) { b . append ( msg ) . append ( "\n" ) ; } b . append ( argp . usage ( ) ) ; return b . toString ( ) ; }
Returns an extended usage banner with optional prefixed messages one per line .
7,158
public static void log ( String format , Object ... args ) { System . out . println ( String . format ( format , args ) ) ; }
System out logger
7,159
public static String processConfigValue ( CharSequence text ) { final String pv = evaluate ( tokenReplaceSysProps ( text ) ) ; return ( pv == null || pv . trim ( ) . isEmpty ( ) ) ? null : pv ; }
Performs sys - prop and js evals on the passed value
7,160
public static String tokenReplaceSysProps ( CharSequence text ) { if ( text == null ) return null ; Matcher m = SYS_PROP_PATTERN . matcher ( text ) ; StringBuffer ret = new StringBuffer ( ) ; while ( m . find ( ) ) { String replacement = decodeToken ( m . group ( 1 ) , m . group ( 2 ) == null ? "<null>" : m . group ( 2 ) ) ; if ( replacement == null ) { throw new IllegalArgumentException ( "Failed to fill in SystemProperties for expression with no default [" + text + "]" ) ; } if ( IS_WINDOWS ) { replacement = replacement . replace ( File . separatorChar , '/' ) ; } m . appendReplacement ( ret , replacement ) ; } m . appendTail ( ret ) ; return ret . toString ( ) ; }
Replaces all matched tokens with the matching system property value or a configured default
7,161
public static String evaluate ( CharSequence text ) { if ( text == null ) return null ; Matcher m = JS_PATTERN . matcher ( text ) ; StringBuffer ret = new StringBuffer ( ) ; final boolean isNas = scriptEngine . getFactory ( ) . getEngineName ( ) . toLowerCase ( ) . contains ( "nashorn" ) ; while ( m . find ( ) ) { String source = ( isNas ? "load(\"nashorn:mozilla_compat.js\");\nimportPackage(java.lang); " : "\nimportPackage(java.lang); " ) + m . group ( 1 ) ; try { Object obj = scriptEngine . eval ( source , bindings ) ; if ( obj != null ) { m . appendReplacement ( ret , obj . toString ( ) ) ; } else { m . appendReplacement ( ret , "" ) ; } } catch ( Exception ex ) { ex . printStackTrace ( System . err ) ; throw new IllegalArgumentException ( "Failed to evaluate expression [" + text + "]" ) ; } } m . appendTail ( ret ) ; return ret . toString ( ) ; }
Evaluates JS expressions defines as configuration values
7,162
public boolean hasNonOption ( String nonOptionKey ) { if ( nonOptionArgs == null || nonOptionArgs . length == 0 || nonOptionKey == null || nonOptionKey . trim ( ) . isEmpty ( ) ) return false ; return Arrays . binarySearch ( nonOptionArgs , nonOptionKey ) >= 0 ; }
Determines if the passed key is contained in the non option args
7,163
private final SearchQuery parseQueryString ( final HttpQuery query , final SearchType type ) { final SearchQuery search_query = new SearchQuery ( ) ; if ( type == SearchType . LOOKUP ) { final String query_string = query . getRequiredQueryStringParam ( "m" ) ; search_query . setTags ( new ArrayList < Pair < String , String > > ( ) ) ; try { search_query . setMetric ( Tags . parseWithMetric ( query_string , search_query . getTags ( ) ) ) ; } catch ( IllegalArgumentException e ) { throw new BadRequestException ( "Unable to parse query" , e ) ; } if ( query . hasQueryStringParam ( "limit" ) ) { final String limit = query . getQueryStringParam ( "limit" ) ; try { search_query . setLimit ( Integer . parseInt ( limit ) ) ; } catch ( NumberFormatException e ) { throw new BadRequestException ( "Unable to convert 'limit' to a valid number" ) ; } } return search_query ; } search_query . setQuery ( query . getRequiredQueryStringParam ( "query" ) ) ; if ( query . hasQueryStringParam ( "limit" ) ) { final String limit = query . getQueryStringParam ( "limit" ) ; try { search_query . setLimit ( Integer . parseInt ( limit ) ) ; } catch ( NumberFormatException e ) { throw new BadRequestException ( "Unable to convert 'limit' to a valid number" ) ; } } if ( query . hasQueryStringParam ( "start_index" ) ) { final String idx = query . getQueryStringParam ( "start_index" ) ; try { search_query . setStartIndex ( Integer . parseInt ( idx ) ) ; } catch ( NumberFormatException e ) { throw new BadRequestException ( "Unable to convert 'start_index' to a valid number" ) ; } } if ( query . hasQueryStringParam ( "use_meta" ) ) { search_query . setUseMeta ( Boolean . parseBoolean ( query . getQueryStringParam ( "use_meta" ) ) ) ; } return search_query ; }
Parses required search values from the query string
7,164
public void internalError ( final Exception cause ) { logError ( "Internal Server Error on " + request ( ) . getUri ( ) , cause ) ; if ( this . api_version > 0 ) { switch ( this . api_version ) { case 1 : default : sendReply ( HttpResponseStatus . INTERNAL_SERVER_ERROR , serializer . formatErrorV1 ( cause ) ) ; } return ; } ThrowableProxy tp = new ThrowableProxy ( cause ) ; tp . calculatePackagingData ( ) ; final String pretty_exc = ThrowableProxyUtil . asString ( tp ) ; tp = null ; if ( hasQueryStringParam ( "json" ) ) { final StringBuilder buf = new StringBuilder ( 32 + pretty_exc . length ( ) ) ; buf . append ( "{\"err\":\"" ) ; HttpQuery . escapeJson ( pretty_exc , buf ) ; buf . append ( "\"}" ) ; sendReply ( HttpResponseStatus . INTERNAL_SERVER_ERROR , buf ) ; } else { sendReply ( HttpResponseStatus . INTERNAL_SERVER_ERROR , makePage ( "Internal Server Error" , "Houston, we have a problem" , "<blockquote>" + "<h1>Internal Server Error</h1>" + "Oops, sorry but your request failed due to a" + " server error.<br/><br/>" + "Please try again in 30 seconds.<pre>" + pretty_exc + "</pre></blockquote>" ) ) ; } }
Sends a 500 error page to the client . Handles responses from deprecated API calls as well as newer versioned API calls
7,165
public void badRequest ( final BadRequestException exception ) { logWarn ( "Bad Request on " + request ( ) . getUri ( ) + ": " + exception . getMessage ( ) ) ; if ( this . api_version > 0 ) { switch ( this . api_version ) { case 1 : default : sendReply ( exception . getStatus ( ) , serializer . formatErrorV1 ( exception ) ) ; } return ; } if ( hasQueryStringParam ( "json" ) ) { final StringBuilder buf = new StringBuilder ( 10 + exception . getDetails ( ) . length ( ) ) ; buf . append ( "{\"err\":\"" ) ; HttpQuery . escapeJson ( exception . getMessage ( ) , buf ) ; buf . append ( "\"}" ) ; sendReply ( HttpResponseStatus . BAD_REQUEST , buf ) ; } else { sendReply ( HttpResponseStatus . BAD_REQUEST , makePage ( "Bad Request" , "Looks like it's your fault this time" , "<blockquote>" + "<h1>Bad Request</h1>" + "Sorry but your request was rejected as being" + " invalid.<br/><br/>" + "The reason provided was:<blockquote>" + exception . getMessage ( ) + "</blockquote></blockquote>" ) ) ; } }
Sends an error message to the client . Handles responses from deprecated API calls .
7,166
public void notFound ( ) { logWarn ( "Not Found: " + request ( ) . getUri ( ) ) ; if ( this . api_version > 0 ) { switch ( this . api_version ) { case 1 : default : sendReply ( HttpResponseStatus . NOT_FOUND , serializer . formatNotFoundV1 ( ) ) ; } return ; } if ( hasQueryStringParam ( "json" ) ) { sendReply ( HttpResponseStatus . NOT_FOUND , new StringBuilder ( "{\"err\":\"Page Not Found\"}" ) ) ; } else { sendReply ( HttpResponseStatus . NOT_FOUND , PAGE_NOT_FOUND ) ; } }
Sends a 404 error page to the client . Handles responses from deprecated API calls
7,167
public void redirect ( final String location ) { response ( ) . headers ( ) . set ( "Location" , location ) ; sendReply ( HttpResponseStatus . OK , new StringBuilder ( "<html></head><meta http-equiv=\"refresh\" content=\"0; url=" + location + "\"></head></html>" ) . toString ( ) . getBytes ( this . getCharset ( ) ) ) ; }
Redirects the client s browser to the given location .
7,168
static void escapeJson ( final String s , final StringBuilder buf ) { final int length = s . length ( ) ; int extra = 0 ; for ( int i = 0 ; i < length ; i ++ ) { final char c = s . charAt ( i ) ; switch ( c ) { case '"' : case '\\' : case '\b' : case '\f' : case '\n' : case '\r' : case '\t' : extra ++ ; continue ; } if ( c < 0x001F ) { extra += 4 ; } } if ( extra == 0 ) { buf . append ( s ) ; return ; } buf . ensureCapacity ( buf . length ( ) + length + extra ) ; for ( int i = 0 ; i < length ; i ++ ) { final char c = s . charAt ( i ) ; switch ( c ) { case '"' : buf . append ( '\\' ) . append ( '"' ) ; continue ; case '\\' : buf . append ( '\\' ) . append ( '\\' ) ; continue ; case '\b' : buf . append ( '\\' ) . append ( 'b' ) ; continue ; case '\f' : buf . append ( '\\' ) . append ( 'f' ) ; continue ; case '\n' : buf . append ( '\\' ) . append ( 'n' ) ; continue ; case '\r' : buf . append ( '\\' ) . append ( 'r' ) ; continue ; case '\t' : buf . append ( '\\' ) . append ( 't' ) ; continue ; } if ( c < 0x001F ) { buf . append ( '\\' ) . append ( 'u' ) . append ( '0' ) . append ( '0' ) . append ( ( char ) Const . HEX [ ( c >>> 4 ) & 0x0F ] ) . append ( ( char ) Const . HEX [ c & 0x0F ] ) ; } else { buf . append ( c ) ; } } }
Escapes a string appropriately to be a valid in JSON . Valid JSON strings are defined in RFC 4627 Section 2 . 5 .
7,169
public void done ( ) { final int processing_time = processingTimeMillis ( ) ; httplatency . add ( processing_time ) ; logInfo ( "HTTP " + request ( ) . getUri ( ) + " done in " + processing_time + "ms" ) ; deferred . callback ( null ) ; }
Method to call after writing the HTTP response to the wire .
7,170
private String guessMimeType ( final ChannelBuffer buf ) { final String mimetype = guessMimeTypeFromUri ( request ( ) . getUri ( ) ) ; return mimetype == null ? guessMimeTypeFromContents ( buf ) : mimetype ; }
Returns the result of an attempt to guess the MIME type of the response .
7,171
private static String guessMimeTypeFromUri ( final String uri ) { final int questionmark = uri . indexOf ( '?' , 1 ) ; final int end = ( questionmark > 0 ? questionmark : uri . length ( ) ) - 1 ; if ( end < 5 ) { return null ; } final char a = uri . charAt ( end - 3 ) ; final char b = uri . charAt ( end - 2 ) ; final char c = uri . charAt ( end - 1 ) ; switch ( uri . charAt ( end ) ) { case 'g' : return a == '.' && b == 'p' && c == 'n' ? "image/png" : null ; case 'l' : return a == 'h' && b == 't' && c == 'm' ? HTML_CONTENT_TYPE : null ; case 's' : if ( a == '.' && b == 'c' && c == 's' ) { return "text/css" ; } else if ( b == '.' && c == 'j' ) { return "text/javascript" ; } else { break ; } case 'f' : return a == '.' && b == 'g' && c == 'i' ? "image/gif" : null ; case 'o' : return a == '.' && b == 'i' && c == 'c' ? "image/x-icon" : null ; } return null ; }
Attempts to guess the MIME type by looking at the URI requested .
7,172
private String guessMimeTypeFromContents ( final ChannelBuffer buf ) { if ( ! buf . readable ( ) ) { logWarn ( "Sending an empty result?! buf=" + buf ) ; return "text/plain" ; } final int firstbyte = buf . getUnsignedByte ( buf . readerIndex ( ) ) ; switch ( firstbyte ) { case '<' : return HTML_CONTENT_TYPE ; case '{' : case '[' : return "application/json" ; case 0x89 : return "image/png" ; } return "text/plain" ; }
Simple content sniffing . May not be a great idea but will do until this class has a better API .
7,173
public static StringBuilder makePage ( final String htmlheader , final String title , final String subtitle , final String body ) { final StringBuilder buf = new StringBuilder ( BOILERPLATE_LENGTH + ( htmlheader == null ? 0 : htmlheader . length ( ) ) + title . length ( ) + subtitle . length ( ) + body . length ( ) ) ; buf . append ( PAGE_HEADER_START ) . append ( title ) . append ( PAGE_HEADER_MID ) ; if ( htmlheader != null ) { buf . append ( htmlheader ) ; } buf . append ( PAGE_HEADER_END_BODY_START ) . append ( subtitle ) . append ( PAGE_BODY_MID ) . append ( body ) . append ( PAGE_FOOTER ) ; return buf ; }
Easy way to generate a small simple HTML page .
7,174
public static void addDataOptions ( final ArgP argp ) { argp . addOption ( "--full-scan" , "Scan the entire data table." ) ; argp . addOption ( "--fix" , "Fix errors as they're found. Use in combination with" + " other flags." ) ; argp . addOption ( "--fix-all" , "Set all flags and fix errors as they're found." ) ; argp . addOption ( "--compact" , "Compacts rows after parsing." ) ; argp . addOption ( "--resolve-duplicates" , "Keeps the oldest (default) or newest duplicates. See --last-write-wins" ) ; argp . addOption ( "--last-write-wins" , "Last data point written will be kept when fixing duplicates.\n" + " May be set via config file and the 'tsd.storage.fix_duplicates' option." ) ; argp . addOption ( "--delete-orphans" , "Delete any time series rows where one or more UIDs fail resolution." ) ; argp . addOption ( "--delete-unknown-columns" , "Delete any unrecognized column that doesn't belong to OpenTSDB." ) ; argp . addOption ( "--delete-bad-values" , "Delete single column datapoints with bad values." ) ; argp . addOption ( "--delete-bad-rows" , "Delete rows with invalid keys." ) ; argp . addOption ( "--delete-bad-compacts" , "Delete compacted columns that cannot be parsed." ) ; argp . addOption ( "--threads" , "NUMBER" , "Number of threads to use when executing a full table scan." ) ; argp . addOption ( "--sync" , "Wait for each fix operation to finish to continue." ) ; }
Add data table fsck options to the command line parser
7,175
private DataPoints abs ( final DataPoints points ) { final List < DataPoint > dps = new ArrayList < DataPoint > ( ) ; final SeekableView view = points . iterator ( ) ; while ( view . hasNext ( ) ) { DataPoint pt = view . next ( ) ; if ( pt . isInteger ( ) ) { dps . add ( MutableDataPoint . ofLongValue ( pt . timestamp ( ) , Math . abs ( pt . longValue ( ) ) ) ) ; } else { dps . add ( MutableDataPoint . ofDoubleValue ( pt . timestamp ( ) , Math . abs ( pt . doubleValue ( ) ) ) ) ; } } final DataPoint [ ] results = new DataPoint [ dps . size ( ) ] ; dps . toArray ( results ) ; return new PostAggregatedDataPoints ( points , results ) ; }
Iterate over each data point and store the absolute value
7,176
private void processParsedValue ( final String parsed_value ) { if ( rule . getCompiledRegex ( ) == null && ( rule . getSeparator ( ) == null || rule . getSeparator ( ) . isEmpty ( ) ) ) { setCurrentName ( parsed_value , parsed_value ) ; } else if ( rule . getCompiledRegex ( ) != null ) { processRegexRule ( parsed_value ) ; } else if ( rule . getSeparator ( ) != null && ! rule . getSeparator ( ) . isEmpty ( ) ) { processSplit ( parsed_value ) ; } else { throw new IllegalStateException ( "Unable to find a processor for rule: " + rule ) ; } }
Routes the parsed value to the proper processing method for altering the display name depending on the current rule . This can route to the regex handler or the split processor . Or if neither splits or regex are specified for the rule the parsed value is set as the branch name .
7,177
private void processRegexRule ( final String parsed_value ) { if ( rule . getCompiledRegex ( ) == null ) { throw new IllegalArgumentException ( "Regex was null for rule: " + rule ) ; } final Matcher matcher = rule . getCompiledRegex ( ) . matcher ( parsed_value ) ; if ( matcher . find ( ) ) { if ( matcher . groupCount ( ) >= rule . getRegexGroupIdx ( ) + 1 ) { final String extracted = matcher . group ( rule . getRegexGroupIdx ( ) + 1 ) ; if ( extracted == null || extracted . isEmpty ( ) ) { testMessage ( "Extracted value for rule " + rule + " was null or empty" ) ; } else { setCurrentName ( parsed_value , extracted ) ; } } else { testMessage ( "Regex group index [" + rule . getRegexGroupIdx ( ) + "] for rule " + rule + " was out of bounds [" + matcher . groupCount ( ) + "]" ) ; } } }
Runs the parsed string through a regex and attempts to extract a value from the specified group index . Group indexes start at 0 . If the regex was not matched or an extracted value for the requested group did not exist then the processor returns and the rule will be considered a no - match .
7,178
private void resetState ( ) { meta = null ; splits = null ; rule_idx = 0 ; split_idx = 0 ; current_branch = null ; rule = null ; not_matched = null ; if ( root != null ) { if ( root . getBranches ( ) != null ) { root . getBranches ( ) . clear ( ) ; } if ( root . getLeaves ( ) != null ) { root . getLeaves ( ) . clear ( ) ; } } test_messages = new ArrayList < String > ( ) ; }
Resets local state variables to their defaults
7,179
public final Deferred < Object > sinkDataPoint ( final String metric , final long timestamp , final byte [ ] value , final Map < String , String > tags , final byte [ ] tsuid , final short flags ) { if ( ( flags & Const . FLAG_FLOAT ) != 0x0 ) { return publishDataPoint ( metric , timestamp , Internal . extractFloatingPointValue ( value , 0 , ( byte ) flags ) , tags , tsuid ) ; } else { return publishDataPoint ( metric , timestamp , Internal . extractIntegerValue ( value , 0 , ( byte ) flags ) , tags , tsuid ) ; } }
Called by the TSD when a new raw data point is published . Because this is called after a data point is queued the value has been converted to a byte array so we need to convert it back to an integer or floating point value . Instead of requiring every implementation to perform the calculation we perform it here and let the implementer deal with the integer or float .
7,180
public Deferred < Object > publishHistogramPoint ( final String metric , final long timestamp , final byte [ ] value , final Map < String , String > tags , final byte [ ] tsuid ) { throw new UnsupportedOperationException ( "Not yet implemented" ) ; }
Called any time a new histogram point is published
7,181
void validateAndCompile ( ) { if ( temporal_table_name == null || temporal_table_name . isEmpty ( ) ) { throw new IllegalArgumentException ( "The rollup table cannot be null or empty" ) ; } temporal_table = temporal_table_name . getBytes ( Const . ASCII_CHARSET ) ; if ( groupby_table_name == null || groupby_table_name . isEmpty ( ) ) { throw new IllegalArgumentException ( "The pre-aggregate rollup table cannot" + " be null or empty" ) ; } groupby_table = groupby_table_name . getBytes ( Const . ASCII_CHARSET ) ; if ( units != 'h' && unit_multiplier > 1 ) { throw new IllegalArgumentException ( "Multipliers are only usable with the 'h' unit" ) ; } else if ( units == 'h' && unit_multiplier > 1 && unit_multiplier % 2 != 0 ) { throw new IllegalArgumentException ( "The multiplier must be 1 or an even value" ) ; } interval = ( int ) ( DateTime . parseDuration ( string_interval ) / 1000 ) ; if ( interval < 1 ) { throw new IllegalArgumentException ( "Millisecond intervals are not supported" ) ; } if ( interval >= Integer . MAX_VALUE ) { throw new IllegalArgumentException ( "Interval is too big: " + interval ) ; } interval_units = string_interval . charAt ( string_interval . length ( ) - 1 ) ; int num_span = 0 ; switch ( units ) { case 'h' : num_span = MAX_SECONDS_IN_HOUR ; break ; case 'd' : num_span = MAX_SECONDS_IN_DAY ; break ; case 'n' : num_span = MAX_SECONDS_IN_MONTH ; break ; case 'y' : num_span = MAX_SECONDS_IN_YEAR ; break ; default : throw new IllegalArgumentException ( "Unrecogznied span '" + units + "'" ) ; } num_span *= unit_multiplier ; if ( interval >= num_span ) { throw new IllegalArgumentException ( "Interval [" + interval + "] is too large for the span [" + units + "]" ) ; } intervals = num_span / ( int ) interval ; if ( intervals > MAX_INTERVALS ) { throw new IllegalArgumentException ( "Too many intervals [" + intervals + "] in the span. Must be smaller than [" + MAX_INTERVALS + "] to fit in 14 bits" ) ; } if ( intervals < MIN_INTERVALS ) { throw new IllegalArgumentException ( "Not enough intervals [" + intervals + "] for the span. Must be at least [" + MIN_INTERVALS + "]" ) ; } }
Calculates the number of intervals in a given span for the rollup interval and makes sure we have table names . It also sets the table byte arrays .
7,182
public byte [ ] getBytes ( ) { final byte [ ] bytes = new byte [ qualifier . length + value . length ] ; System . arraycopy ( this . qualifier , 0 , bytes , 0 , qualifier . length ) ; System . arraycopy ( value , 0 , bytes , qualifier . length , value . length ) ; return bytes ; }
Concatenates the qualifier and value for appending to a column in the backing data store .
7,183
static long getMaxMetricID ( final TSDB tsdb ) { final GetRequest get = new GetRequest ( tsdb . uidTable ( ) , new byte [ ] { 0 } ) ; get . family ( "id" . getBytes ( CHARSET ) ) ; get . qualifier ( "metrics" . getBytes ( CHARSET ) ) ; ArrayList < KeyValue > row ; try { row = tsdb . getClient ( ) . get ( get ) . joinUninterruptibly ( ) ; if ( row == null || row . isEmpty ( ) ) { return 0 ; } final byte [ ] id_bytes = row . get ( 0 ) . value ( ) ; if ( id_bytes . length != 8 ) { throw new IllegalStateException ( "Invalid metric max UID, wrong # of bytes" ) ; } return Bytes . getLong ( id_bytes ) ; } catch ( Exception e ) { throw new RuntimeException ( "Shouldn't be here" , e ) ; } }
Returns the max metric ID from the UID table
7,184
static final Scanner getDataTableScanner ( final TSDB tsdb , final long start_id , final long end_id ) throws HBaseException { final short metric_width = TSDB . metrics_width ( ) ; final byte [ ] start_row = Arrays . copyOfRange ( Bytes . fromLong ( start_id ) , 8 - metric_width , 8 ) ; final byte [ ] end_row = Arrays . copyOfRange ( Bytes . fromLong ( end_id ) , 8 - metric_width , 8 ) ; final Scanner scanner = tsdb . getClient ( ) . newScanner ( tsdb . dataTable ( ) ) ; scanner . setStartKey ( start_row ) ; scanner . setStopKey ( end_row ) ; scanner . setFamily ( TSDB . FAMILY ( ) ) ; return scanner ; }
Returns a scanner set to iterate over a range of metrics in the main tsdb - data table .
7,185
private List < Filter > getFilters ( final boolean group_by ) { final int ntags = getNumTags ( ) ; final List < Filter > filters = new ArrayList < Filter > ( ntags ) ; for ( int tag = 0 ; tag < ntags ; tag ++ ) { final Filter filter = new Filter ( ) ; filter . tagk = getTagName ( tag ) ; filter . tagv = getTagValue ( tag ) ; filter . is_groupby = isTagGroupby ( tag ) ; if ( filter . tagk . isEmpty ( ) || filter . tagv . isEmpty ( ) ) { continue ; } if ( filter . is_groupby == group_by ) { filters . add ( filter ) ; } } Collections . sort ( filters ) ; return filters ; }
Helper method to extract the tags from the row set and sort them before sending to the API so that we avoid a bug wherein the sort order changes on reload .
7,186
private void setSelectedItem ( final ListBox list , final String item ) { final int nitems = list . getItemCount ( ) ; for ( int i = 0 ; i < nitems ; i ++ ) { if ( item . equals ( list . getValue ( i ) ) ) { list . setSelectedIndex ( i ) ; return ; } } }
If the given item is in the list mark it as selected .
7,187
public static HashedWheelTimer newTimer ( final int ticks , final int ticks_per_wheel , final String name ) { class TimerThreadNamer implements ThreadNameDeterminer { public String determineThreadName ( String currentThreadName , String proposedThreadName ) throws Exception { return "OpenTSDB Timer " + name + " #" + TIMER_ID . incrementAndGet ( ) ; } } return new HashedWheelTimer ( Executors . defaultThreadFactory ( ) , new TimerThreadNamer ( ) , ticks , MILLISECONDS , ticks_per_wheel ) ; }
Returns a new HashedWheelTimer with a name and default ticks
7,188
public void validate ( ) { if ( interval == null || interval . isEmpty ( ) ) { throw new IllegalArgumentException ( "Missing or empty interval" ) ; } DateTime . parseDuration ( interval ) ; if ( aggregator == null || aggregator . isEmpty ( ) ) { throw new IllegalArgumentException ( "Missing or empty aggregator" ) ; } try { Aggregators . get ( aggregator . toLowerCase ( ) ) ; } catch ( final NoSuchElementException e ) { throw new IllegalArgumentException ( "Invalid aggregator" ) ; } if ( fill_policy != null ) { fill_policy . validate ( ) ; } }
Validates the downsampler
7,189
public void validate ( ) { if ( policy == null ) { if ( value == 0 ) { policy = FillPolicy . ZERO ; } else if ( Double . isNaN ( value ) ) { policy = FillPolicy . NOT_A_NUMBER ; } else { policy = FillPolicy . SCALAR ; } } else { switch ( policy ) { case NONE : case NOT_A_NUMBER : if ( value != 0 && ! Double . isNaN ( value ) ) { throw new IllegalArgumentException ( "The value for NONE and NAN must be NaN" ) ; } value = Double . NaN ; break ; case ZERO : if ( value != 0 ) { throw new IllegalArgumentException ( "The value for ZERO must be 0" ) ; } value = 0 ; break ; case NULL : if ( value != 0 && ! Double . isNaN ( value ) ) { throw new IllegalArgumentException ( "The value for NULL must be 0" ) ; } value = Double . NaN ; break ; case SCALAR : break ; } } }
Makes sure the policy name and value are a suitable combination . If one or the other is missing then we set the other with the proper value .
7,190
public HistogramDataPointCodec getCodec ( final int id ) { final HistogramDataPointCodec codec = codecs . get ( id ) ; if ( codec == null ) { throw new IllegalArgumentException ( "No codec found mapped to ID " + id ) ; } return codec ; }
Return the instance of the given codec .
7,191
public int getCodec ( final Class < ? > clazz ) { if ( clazz == null ) { throw new IllegalArgumentException ( "Clazz cannot be null." ) ; } final Integer id = codecs_ids . get ( clazz ) ; if ( id == null ) { throw new IllegalArgumentException ( "No codec ID assigned to class " + clazz ) ; } return id ; }
Return the ID of the given codec .
7,192
public byte [ ] encode ( final int id , final Histogram data_point , final boolean include_id ) { final HistogramDataPointCodec codec = getCodec ( id ) ; return codec . encode ( data_point , include_id ) ; }
Finds the proper codec and calls it s encode method to create a byte array with the given ID as the first byte .
7,193
public Histogram decode ( final int id , final byte [ ] raw_data , final boolean includes_id ) { final HistogramDataPointCodec codec = getCodec ( id ) ; return codec . decode ( raw_data , includes_id ) ; }
Finds the proper codec and calls it s decode method to return the histogram data point for queries or validation .
7,194
public Deferred < Object > execute ( final TSDB tsdb , final Channel chan , final String [ ] cmd ) { final boolean canonical = tsdb . getConfig ( ) . getBoolean ( "tsd.stats.canonical" ) ; final StringBuilder buf = new StringBuilder ( 1024 ) ; final ASCIICollector collector = new ASCIICollector ( "tsd" , buf , null ) ; doCollectStats ( tsdb , collector , canonical ) ; chan . write ( buf . toString ( ) ) ; return Deferred . fromResult ( null ) ; }
Telnet RPC responder that returns the stats in ASCII style
7,195
public void execute ( final TSDB tsdb , final HttpQuery query ) { if ( query . method ( ) != HttpMethod . GET && query . method ( ) != HttpMethod . POST ) { throw new BadRequestException ( HttpResponseStatus . METHOD_NOT_ALLOWED , "Method not allowed" , "The HTTP method [" + query . method ( ) . getName ( ) + "] is not permitted for this endpoint" ) ; } try { final String [ ] uri = query . explodeAPIPath ( ) ; final String endpoint = uri . length > 1 ? uri [ 1 ] . toLowerCase ( ) : "" ; if ( "threads" . equals ( endpoint ) ) { printThreadStats ( query ) ; return ; } else if ( "jvm" . equals ( endpoint ) ) { printJVMStats ( tsdb , query ) ; return ; } else if ( "query" . equals ( endpoint ) ) { printQueryStats ( query ) ; return ; } else if ( "region_clients" . equals ( endpoint ) ) { printRegionClientStats ( tsdb , query ) ; return ; } } catch ( IllegalArgumentException e ) { } final boolean canonical = tsdb . getConfig ( ) . getBoolean ( "tsd.stats.canonical" ) ; if ( query . apiVersion ( ) < 1 ) { final boolean json = query . hasQueryStringParam ( "json" ) ; final StringBuilder buf = json ? null : new StringBuilder ( 2048 ) ; final ArrayList < String > stats = json ? new ArrayList < String > ( 64 ) : null ; final ASCIICollector collector = new ASCIICollector ( "tsd" , buf , stats ) ; doCollectStats ( tsdb , collector , canonical ) ; if ( json ) { query . sendReply ( JSON . serializeToBytes ( stats ) ) ; } else { query . sendReply ( buf ) ; } return ; } final List < IncomingDataPoint > dps = new ArrayList < IncomingDataPoint > ( 64 ) ; final SerializerCollector collector = new SerializerCollector ( "tsd" , dps , canonical ) ; ConnectionManager . collectStats ( collector ) ; RpcHandler . collectStats ( collector ) ; RpcManager . collectStats ( collector ) ; tsdb . collectStats ( collector ) ; query . sendReply ( query . serializer ( ) . formatStatsV1 ( dps ) ) ; }
HTTP resposne handler
7,196
private void doCollectStats ( final TSDB tsdb , final StatsCollector collector , final boolean canonical ) { collector . addHostTag ( canonical ) ; ConnectionManager . collectStats ( collector ) ; RpcHandler . collectStats ( collector ) ; RpcManager . collectStats ( collector ) ; collectThreadStats ( collector ) ; tsdb . collectStats ( collector ) ; }
Helper to record the statistics for the current TSD
7,197
private void printRegionClientStats ( final TSDB tsdb , final HttpQuery query ) { final List < RegionClientStats > region_stats = tsdb . getClient ( ) . regionStats ( ) ; final List < Map < String , Object > > stats = new ArrayList < Map < String , Object > > ( region_stats . size ( ) ) ; for ( final RegionClientStats rcs : region_stats ) { final Map < String , Object > stat_map = new HashMap < String , Object > ( 8 ) ; stat_map . put ( "rpcsSent" , rcs . rpcsSent ( ) ) ; stat_map . put ( "rpcsInFlight" , rcs . inflightRPCs ( ) ) ; stat_map . put ( "pendingRPCs" , rcs . pendingRPCs ( ) ) ; stat_map . put ( "pendingBatchedRPCs" , rcs . pendingBatchedRPCs ( ) ) ; stat_map . put ( "dead" , rcs . isDead ( ) ) ; stat_map . put ( "rpcid" , rcs . rpcID ( ) ) ; stat_map . put ( "endpoint" , rcs . remoteEndpoint ( ) ) ; stat_map . put ( "rpcsTimedout" , rcs . rpcsTimedout ( ) ) ; stat_map . put ( "rpcResponsesTimedout" , rcs . rpcResponsesTimedout ( ) ) ; stat_map . put ( "rpcResponsesUnknown" , rcs . rpcResponsesUnknown ( ) ) ; stat_map . put ( "inflightBreached" , rcs . inflightBreached ( ) ) ; stat_map . put ( "pendingBreached" , rcs . pendingBreached ( ) ) ; stat_map . put ( "writesBlocked" , rcs . writesBlocked ( ) ) ; stats . add ( stat_map ) ; } query . sendReply ( query . serializer ( ) . formatRegionStatsV1 ( stats ) ) ; }
Display stats for each region client
7,198
private void printThreadStats ( final HttpQuery query ) { final Set < Thread > threads = Thread . getAllStackTraces ( ) . keySet ( ) ; final List < Map < String , Object > > output = new ArrayList < Map < String , Object > > ( threads . size ( ) ) ; for ( final Thread thread : threads ) { final Map < String , Object > status = new HashMap < String , Object > ( ) ; status . put ( "threadID" , thread . getId ( ) ) ; status . put ( "name" , thread . getName ( ) ) ; status . put ( "state" , thread . getState ( ) . toString ( ) ) ; status . put ( "interrupted" , thread . isInterrupted ( ) ) ; status . put ( "priority" , thread . getPriority ( ) ) ; final List < String > stack = new ArrayList < String > ( thread . getStackTrace ( ) . length ) ; for ( final StackTraceElement element : thread . getStackTrace ( ) ) { stack . add ( element . toString ( ) ) ; } status . put ( "stack" , stack ) ; output . add ( status ) ; } query . sendReply ( query . serializer ( ) . formatThreadStatsV1 ( output ) ) ; }
Grabs a snapshot of all JVM thread states and formats it in a manner to be displayed via API .
7,199
private void collectThreadStats ( final StatsCollector collector ) { final Set < Thread > threads = Thread . getAllStackTraces ( ) . keySet ( ) ; final Map < String , Integer > states = new HashMap < String , Integer > ( 6 ) ; states . put ( "new" , 0 ) ; states . put ( "runnable" , 0 ) ; states . put ( "blocked" , 0 ) ; states . put ( "waiting" , 0 ) ; states . put ( "timed_waiting" , 0 ) ; states . put ( "terminated" , 0 ) ; for ( final Thread thread : threads ) { int state_count = states . get ( thread . getState ( ) . toString ( ) . toLowerCase ( ) ) ; state_count ++ ; states . put ( thread . getState ( ) . toString ( ) . toLowerCase ( ) , state_count ) ; } for ( final Map . Entry < String , Integer > entry : states . entrySet ( ) ) { collector . record ( "jvm.thread.states" , entry . getValue ( ) , "state=" + entry . getKey ( ) ) ; } collector . record ( "jvm.thread.count" , threads . size ( ) ) ; }
Runs through the live threads and counts captures a coune of their states for dumping in the stats page .